首页 > 解决方案 > 使用 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

解决方案


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

它奏效了。


推荐阅读