Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

powershell - 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 \serversharepic.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:Windowssystem32> 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

$usercreds = Get-Credential
$picPath = "\serversharepic.jpg"
$uri = http://website/sub/destination

Invoke-WebRequest -uri $uri -Method Put -Infile $picPath -ContentType 'image/jpg' -Credential $usercreds

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...