21

I'm trying to send a file via Invoke-RestMethod in a similar context as curl with the -F switch.

Curl Example

curl -F FileName=@"/path-to-file.name" "https://uri-to-post"

In powershell, I've tried something like this:

$uri = "https://uri-to-post"
$contentType = "multipart/form-data"
$body = @{
    "FileName" = Get-Content($filePath) -Raw
}

Invoke-WebRequest -Uri $uri -Method Post -ContentType $contentType -Body $body
}

If I check fiddler I see that the body contains the raw binary data, but I get a 200 response back showing no payload has been sent.

I've also tried to use the -InFile parameter with no luck.

I've seen a number of examples using a .net class, but was trying to keep this simple with the newer Powershell 3 commands.

Does anyone have any guidance or experience making this work?

Jeff
  • 765
  • 2
  • 6
  • 17
  • 1
    Did u tried this -http://stackoverflow.com/questions/12251965/rapidshare-api-with-powershell – Mitul Mar 19 '14 at 04:17
  • 1
    Multipart messages are not supported. You can set the content type to be anything, but setting it to `multipart/form-data` does not cause the message to be formatted as [multipart](http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html). – Don Cruickshank Mar 19 '14 at 13:26
  • 1
    Multipart/form-data does work when adding as content type. The problem I had here is the API needed some parameters to accept raw content, then I was able to use -InFile \path\to\file and upload using Invoke-RestMethod – Jeff Mar 21 '14 at 15:54

4 Answers4

17

The accepted answer won't do a multipart/form-data request, but rather a application/x-www-form-urlencoded request forcing the Content-Type header to a value that the body does not contain.

One way to send a multipart/form-data formatted request with PowerShell is:

$ErrorActionPreference = 'Stop'

$fieldName = 'file'
$filePath = 'C:\Temp\test.pdf'
$url = 'http://posttestserver.com/post.php'

Try {
    Add-Type -AssemblyName 'System.Net.Http'

    $client = New-Object System.Net.Http.HttpClient
    $content = New-Object System.Net.Http.MultipartFormDataContent
    $fileStream = [System.IO.File]::OpenRead($filePath)
    $fileName = [System.IO.Path]::GetFileName($filePath)
    $fileContent = New-Object System.Net.Http.StreamContent($fileStream)
    $content.Add($fileContent, $fieldName, $fileName)

    $result = $client.PostAsync($url, $content).Result
    $result.EnsureSuccessStatusCode()
}
Catch {
    Write-Error $_
    exit 1
}
Finally {
    if ($client -ne $null) { $client.Dispose() }
    if ($content -ne $null) { $content.Dispose() }
    if ($fileStream -ne $null) { $fileStream.Dispose() }
    if ($fileContent -ne $null) { $fileContent.Dispose() }
}
David
  • 3,478
  • 6
  • 30
  • 51
  • Is there a way to supply cookies or credentials with this method? – Jelphy Apr 04 '19 at 16:01
  • If you are going to make multiple HTTP multiple times (i.e. run this in a loop), you shouldn't dispose the `HttpClient ` instance: https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ – Carl Walsh Mar 18 '21 at 18:37
14

The problem here was what the API required some additional parameters. Initial request required some parameters to accept raw content and specify filename/size. After setting that and getting back proper link to submit, I was able to use:

Invoke-RestMethod -Uri $uri -Method Post -InFile $filePath -ContentType "multipart/form-data"
Jeff
  • 765
  • 2
  • 6
  • 17
  • What were the additional parameters you had to add? I'm having the exact same problem using the ShareFile api... – Tyler Jones Aug 15 '14 at 19:50
  • Really depends, did you read http://api.sharefile.com/rest/docs/resource.aspx?name=Items You can try something like this: sf/v3/Items($parentFolderId)/Upload?method=standard&raw=true&fileName=$fileName&fileSize=$fileSize Obviously replacing those variables with your data – Jeff Aug 19 '14 at 00:30
  • 2
    The question I have is was this specific to the API you were trying to use or would this be a general requirement for file uploads using multipart posts? JIRA's [API documentation](https://docs.atlassian.com/jira/REST/latest/#d2e5037) only lists an example with curl (and mentions some header requirements), with no other post parameters. – Ellesedil Aug 27 '14 at 15:31
  • 6
    This doesn't create the multipart body format required, the body will not have the `boundary=------------------------abcdefg1234` parts separating the content. See http://stackoverflow.com/q/25075010/516748 – KCD Feb 14 '17 at 02:41
6

I found this post and changed it a bit

$fileName = "..."
$uri = "..."

$currentPath = Convert-Path .
$filePath="$currentPath\$fileName"

$fileBin = [System.IO.File]::ReadAlltext($filePath)
$boundary = [System.Guid]::NewGuid().ToString()
$LF = "`r`n"
$bodyLines = (
    "--$boundary",
    "Content-Disposition: form-data; name=`"file`"; filename=`"$fileName`"",
    "Content-Type: application/octet-stream$LF",
    $fileBin,
    "--$boundary--$LF"
) -join $LF

Invoke-RestMethod -Uri $uri -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines
kogoia
  • 1,853
  • 3
  • 14
  • 33
0

For anyone wondering (like Jelphy) whether David's answer can be used with cookies/credentials, the answer is yes.

First set the session with Invoke-WebRequest:

Invoke-WebRequest -Uri "$LoginUri" -Method Get -SessionVariable 'Session'

Then POST to the Login URL, which stores the authentication cookie in $Session:

$Response = Invoke-WebRequest -Uri "$Uri" -Method Post -Body $Body -WebSession $Session

The steps above are the standard way to deal with session in Powershell. But here is the important part. Before creating the HttpClient, create an HttpClientHandler and set it's CookieContainer property with the cookies from the session:

$ClientMessageHandler = New-Object System.Net.Http.HttpClientHandler
$ClientMessageHandler.CookieContainer = $Session.Cookies

Then pass this object to the HttpClient constructor

$Client = [System.Net.Http.HttpClient]::new($ClientMessageHandler)

Voila, you now have an HttpClient with session cookies set automatically via Invoke-WebRequest. The rest of David's example should work (copied here for completeness):

$MultipartFormData = New-Object System.Net.Http.MultipartFormDataContent
$FileStream = [System.IO.File]::OpenRead($FilePath)
$FileName = [System.IO.Path]::GetFileName($FilePath)
$FileContent = New-Object System.Net.Http.StreamContent($FileStream)
$MultipartFormData.Add($FileContent, $FieldName, $FileName)

$Result = $Client.PostAsync($url, $content).Result
$Result.EnsureSuccessStatusCode()

I had many files to upload with each request, so I factored out this last bit into a lambda function:

function Add-FormFile {
    param ([string]$Path, [string]$Name)

    if ($Path -ne "")
    {    
        $FileStream = [System.IO.File]::OpenRead($Path)
        $FileName = [System.IO.Path]::GetFileName($Path)
        $FileContent = [System.Net.Http.StreamContent]::new($FileStream)
        $MultipartFormData.Add($FileContent, $Name, $FileName)
    }
}
Chris
  • 300
  • 3
  • 8