powershell - 使用 PowerShell 使用 multipart/form-data 将文件上传到 API 端点
问题描述
此 curl 命令有效:
curl -v -X POST https://subdomain.playvox.com/api/v1/files/upload?context=quality -H "Content-Type: multipart/form-data" -u [username]:[password] -F file=@c:\path\to\file.wav
但我无法使用 Invoke-RestMethod cmdlet 在 PowerShell 中执行相同的操作。这是我的尝试:
$file_contents = [System.IO.File]::ReadAllBytes($($file_path))
Invoke-RestMethod -Uri "https://subdomains.playvox.com/api/v1/files/upload?context=quality" -Method Post -ContentType "multipart/form-data" -Headers @{ "Authorization" = "Basic $($playvox_base64_auth)" } -Body @{ file = $file_contents }
运行 API 以 invalid_param 响应时,需要“file”。但是,我确认对 ReadAllBytes 的调用成功并返回原始文件数据。似乎 PowerShell 没有以正确的格式发送请求正文?我在这里查看了其他几个答案和在线文档,但我发现没有任何效果。
解决方案
发现 Powershell 6 及更高版本中有一个 -Form 参数。我更新了我的 powershell 并使用了以下内容:
$file_contents = Get-Item $file_path
Invoke-RestMethod -Uri "https://subdomains.playvox.com/api/v1/files/upload?context=quality" -Method Post -ContentType "multipart/form-data" -Headers @{ "Authorization" = "Basic $($playvox_base64_auth)" } -Form @{ file = $file_contents }
它奏效了。
推荐阅读
- python - 如何在 django 中使用“self”/它自己的模型获取 ManyToManyField 中的对象数?
- javascript - 错误 TS2339:“特殊 []”类型上不存在属性“默认”
- apache - htaccess:我不能允许来自特定域而不是 IP 的访问
- xslt - 获取第一次出现的 XSLT 样式表
- java - -XX:+PrintCodeCacheOnCompilation 在特定文件中
- java - 如果我有任务执行器,对我的 Spring Boot 应用程序有什么影响
- c - 这是如何运作的?如果我想存储超过 1 个复数,这可行吗?
- python - 熊猫数据框中每一行的最小值
- dataframe - Pyspark 数据框:根据其他列值创建列
- vue.js - Vue,如果我选择一个选项,如何得到一个空行?