2014-03-31 159 views
2

我試圖在PowerShell 3和4中使用Invoke-RestMethod cmdlet來使用REST API的多部分/表單數據上傳上傳大型二進制文件。這裏是如何執行我想要在PowerShell中做工作捲曲例如:使用PowerShell Invoke-RestMethod POST POST大型二進制多部分/表單數據

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" 

我希望能看到關於如何使用調用-RestMethod來發布的multipart/form-data的工作的例子。我發現要上傳到OneDrive(aka SkyDrive)的blog post from the PowerShell team showing how to use Invoke-RestMethod,但效果不佳。如果可能的話,我也想避免使用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" 

我曾嘗試使用調用-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 
+2

我今天在這裏添加了一個有關此問題的答案:http://stackoverflow.com/questions/25075010/upload-multiple-files-from-powershell-script(哦,請更正標題以獲得更好的點擊重置 - >休息) – akauppi

回答

4

我知道你一年前問過,可能解決了這個問題,但對於爲了可能有同樣問題的其他人的緣故,我要離開我的迴應。

我注意到你的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來檢查服務器的響應。

+0

這不會創建所需的多部分正文格式,正文不會有'boundary = ------------------------ abcdefg1234'部分分離內容 – KCD

相關問題