使用PowerShell Invoke-RestMethod来发布大型二进制多部分/表单数据

Chr*_*nch 4 powershell powershell-3.0

我正在尝试使用PowerShell 3和4中的Invoke-RestMethod cmdlet,使用REST API的multipart/form-data上载来上传大型二进制文件.这是一个有关如何在PowerShell中执行我想要执行的操作的cURL示例:

curl -i -k -H "accept: application/json" -H "content-type: multipart/form-data" -H "accept-language: en-us" -H "auth: tokenid" -F file="@Z:\large_binary_file.bin" -X POST "https://server/rest/uri2"
Run Code Online (Sandbox Code Playgroud)

我很想看到一个关于如何使用Invoke-RestMethod来POST多部分/表单数据的工作示例.我在PowerShell团队发现了一篇博文,展示了如何使用Invoke-RestMethod上传到OneDrive(又名SkyDrive),但效果不佳.如果可能的话,我也想避免使用System.Net.WebClient.我还在Stackoverflow上找到了另一个线程,但它确实没有多大帮助.

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }

$server = "https://server"
uri = "/rest/uri1"
$headers = @{"accept" = "application/json"; "content-type" = "application/json";"accept-language" = "en-us"}
$body = @{"userName" = "administrator"; "password" = "password"}
$method = "POST"

#Get Session ID
$resp = Invoke-RestMethod -Method $method -Headers $headers -Uri ($server+$uri) -body (convertto-json $Body -depth 99)

$sessionID = $resp.sessionID

#Upload file
$uri = "/rest/uri2"
$headers = @{"accept" = "application/json";"content-type" = "multipart/form-data"; "accept-        language" = "en-us"; "auth" = $sessionID}
$medthod = "POST"
$largeFile = "Z:\large_binary_file.bin"
Run Code Online (Sandbox Code Playgroud)

我尝试了两种使用Invoke-RestMethod的方法:

Invoke-RestMethod -Method $method -Headers $headers -Uri ($server+$uri) -InFile $largeFile
Run Code Online (Sandbox Code Playgroud)

要么

$body = "file=$(get-content $updateFile -Enc Byte -raw)"
Invoke-RestMethod -Method $method -Headers $headers -Uri ($server+$uri) -body $body
Run Code Online (Sandbox Code Playgroud)

KMC*_*KMC 9

我知道你在一年前问过并且可能已经解决了这个问题,但是为了其他可能有同样问题的人,我会离开我的回答.

我注意到你的invoke语句中有几个错误.首先,您需要使用POST关键字而不是字符串值.其次,确保将Content-Type设置为multipart/form-data.所以这是我修改后的声明 -

$uri = "http://blahblah.com"
$imagePath = "c:/justarandompic.jpg"
$upload= Invoke-RestMethod -Uri $uri -Method Post -InFile $imagePath -ContentType 'multipart/form-data' 
Run Code Online (Sandbox Code Playgroud)

您可以通过选中$ upload来检查服务器的响应.

  • 这不会创建所需的多部分正文格式,正文将没有分隔内容的 `boundary=------------------------abcdefg1234` 部分 (3认同)