5

I'm trying to use the Invoke-RestMethod cmdlet in PowerShell 3 and 4, to upload a large binary file using a REST API's multipart/form-data upload. Here is a working cURL example on how to perform what I want to do in PowerShell:

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"

I would love to see a working example on how to use Invoke-RestMethod to POST a multipart/form-data. I found a blog post from the PowerShell team showing how to use Invoke-RestMethod to upload to OneDrive (aka SkyDrive), but doesn't work well. I'd also like to avoid using System.Net.WebClient if at all possible. I also found another thread here on Stackoverflow, but it really didn't help much.

[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"

I have tried both ways of using Invoke-RestMethod:

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

or

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

1 Answer 1

11

I notice couple of mistakes in your invoke statement. First, you need to use POST keyword instead of string value. Second, make sure that Content-Type is set to multipart/form-data. So this is my revised statement -

$uri = "http://blahblah.com"
$imagePath = "c:/justarandompic.jpg"
$upload= Invoke-RestMethod -Uri $uri -Method Post -InFile $imagePath -ContentType 'multipart/form-data' 

You can check the response from the server by checking $upload.

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't create the multipart body format required, the body will not have the boundary=------------------------abcdefg1234 parts separating the content

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.