Welcome to OGeek Q&A 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...