How to use Invoke-RestMethod to upload jpg

I've been trying for a day to get this working. My setup was a powershell script that was pushing a screenshot into a nodejs express api endpoint that was saving to the server. The above code almost worked, that is, the endpoint was hit and the file was saved, but the whatever was being saved wasn't the right encoding. I searched high and low for a solution, used multiple frameworks like multer, formidable, busboy etc. Tried various methods that involved building up the body for a multipart form, but with the same results.

What worked in the end for me (in case anyone else is reading) was to send it as base64 data and convert it on the other end because something wasn't going right with the encoding and I couldn't work it out.

Powershell script ($path and $uri are as above, nothing different)

$base64Image = [convert]::ToBase64String((get-content $path -encoding byte))
Invoke-WebRequest -uri $uri -Method Post -Body $base64Image -ContentType "application/base64"

Nodejs Express


app.post("/api/screenshot/", (req,res) => {
    let body = '';
    req.on('data', chunk => {
        body += chunk.toString();
    });
    req.on('end', () => {
      fs.writeFile(__dirname + '/public/images/a.jpg', body,'base64',function(err) {
        if( err ) {
          res.end('not okay');
        } else {
          res.end('ok');
        }
      });
    });
});

Probably more inefficient, but I needed to get something working.


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

Tags:

Powershell