【问题标题】:Using PowerShell Invoke-RestMethod to POST large binary multipart/form-data使用 PowerShell Invoke-RestMethod 发布大型二进制多部分/表单数据
【发布时间】:2014-03-31 19:15:48
【问题描述】:

我正在尝试使用 PowerShell 3 和 4 中的 Invoke-RestMethod cmdlet,通过 REST API 的多部分/表单数据上传来上传大型二进制文件。这是一个关于如何在 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"

我希望看到一个关于如何使用 Invoke-RestMethod 发布多部分/表单数据的工作示例。我找到了一个blog post from the PowerShell team showing how to use Invoke-RestMethod 来上传到 OneDrive(又名 SkyDrive),但效果不佳。如果可能的话,我还想避免使用 System.Net.WebClient。我还找到了another thread here on 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"

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

Invoke-RestMethod -Method $method -Headers $headers -Uri ($server+$uri) -InFile $largeFile

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

【问题讨论】:

标签: powershell powershell-3.0


【解决方案1】:

我注意到您的调用语句中有几个错误。首先,您需要使用 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' 

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

【讨论】:

  • 这不会创建所需的多部分正文格式,正文将没有boundary=------------------------abcdefg1234 分隔内容的部分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多