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

时间:2014-03-31 19:15:48

标签: powershell powershell-v3.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"

我很想看到一个关于如何使用Invoke-RestMethod来发布multipart / form-data的实例。我找到了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

1 个答案:

答案 0 :(得分: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' 

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