Search code examples
powershellfile-upload

How to use Invoke-RestMethod to upload jpg


I'm trying to use the PowerShell commandlet Invoke-RestMethod to post a picture to a url. Here's my commands:

$usercreds = Get-Credential
$pic = Get-Content \\server\share\pic.jpg
$uri = http://website/sub/destination

Invoke-RestMethod -uri $uri -Method Put -Body $pic -ContentType 'image/jpg' -Credential $usercreds

I get an error: "the file is not a valid image file." I tried using Invoke-WebRequest too, with the same result. The web server isn't ours, and the tech on their side said to use curl, but we don't know how and don't have a Linux box either. Is there something I'm missing? I can open the jpg without issue so it's not corrupt or anything.

I tried this, but the server yelled at me: Using PowerShell Invoke-RestMethod to POST large binary multipart/form-data

Error code:

PS C:\Windows\system32> Invoke-WebRequest -uri $uri -Method Put -Body $pic -ContentType 'image/jpg' -Credential $usercreds
Invoke-WebRequest : {"error":{"message":"the file is not a valid image file"},"data":[],"meta":"error"}
At line:1 char:1
+ Invoke-WebRequest -uri $uri -Method Put -Body $pic -ContentType 'imag ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Solution

  • Try using the -Infile Parameter. Get-Content interprets your file an array of strings and just messes things up.

    $usercreds = Get-Credential
    $picPath = "\\server\share\pic.jpg"
    $uri = http://website/sub/destination
    
    Invoke-WebRequest -uri $uri -Method Put -Infile $picPath -ContentType 'image/jpg' -Credential $usercreds