Search code examples
restpowershellcurl

powershell invoke-restmethod multipart/form-data


I'm currently trying to upload a file to a Webserver by using a REST API. And as mentioned I'm using PowerShell for this. With curl this is no problem. The call looks like this:

curl -H "Auth_token:"$AUTH_TOKEN -H "Content-Type:multipart/form-data" -X POST -F appInfo='{"name": "test","description": "test"}' -F uploadFile=@/test/test.test https://server/api/

But I'm completely helpless when it comes to exporting this to powershell with a Invoke-Restmethod command. As far as I searched it is not possible to use the Invoke-Restmethod for this.

I would be very thankful if someone could get me back on the track with this :o Thanks!


Solution

  • It should be pretty straight forward. Taking from this answer:

    $Uri = 'https://server/api/';
    $Headers = @{'Auth_token'=$AUTH_TOKEN};
    $FileContent = [IO.File]::ReadAllText('C:\test\test.test');
    $Fields = @{'appInfo'='{"name": "test","description": "test"}';'uploadFile'=$FileContent};
    
    Invoke-RestMethod -Uri $Uri -ContentType 'multipart/form-data' -Method Post -Headers $Headers -Body $Fields;
    

    You may want to use [IO.File]::ReadAllBytes() if the file isn't a text file.

    This also may not work well if you're uploading a huge file.