【问题标题】:Upload file to API endpoint with PowerShell using multipart/form-data使用 PowerShell 使用 multipart/form-data 将文件上传到 API 端点
【发布时间】:2021-03-23 15:17:53
【问题描述】:

此 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 没有以正确的格式发送请求正文?我在这里查看了其他几个答案和在线文档,但我发现没有任何效果。

【问题讨论】:

  • 您还尝试了哪些其他解决方案?这里有一些不同的回答似乎是不错的候选人。您是否尝试过使用 .NET webclient 类并使用它来上传? stackoverflow.com/questions/38164723/… 看起来更高版本的 PowerShell 有一个 -InFile 参数,如果 PS 版本不适合您:docs.microsoft.com/en-us/powershell/module/…
  • @Efie 我试过 -InFile 但这不起作用,因为端点需要一个名为“file”的表单属性。同样对于webclient类的UploadFile函数,它只需要uri和文件路径,无法模拟我可以看到的表单属性。

标签: powershell


【解决方案1】:

发现 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 }

它奏效了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 2015-10-23
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    相关资源
    最近更新 更多