powershell invoke-restmethod multipart/form-data

后端 未结 6 611
不思量自难忘°
不思量自难忘° 2020-12-01 09:50

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

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 10:24

    @Bacon-Bits answer didn't seem to work for me. My server rejected it with a potentially malformed form-data body :-(

    I found this gist, and trimmed it up a bit for my purposes. Here's my end result:

    $FilePath = 'c:\temp\temp.txt';
    $URL = 'http://your.url.here';
    
    $fileBytes = [System.IO.File]::ReadAllBytes($FilePath);
    $fileEnc = [System.Text.Encoding]::GetEncoding('UTF-8').GetString($fileBytes);
    $boundary = [System.Guid]::NewGuid().ToString(); 
    $LF = "`r`n";
    
    $bodyLines = ( 
        "--$boundary",
        "Content-Disposition: form-data; name=`"file`"; filename=`"temp.txt`"",
        "Content-Type: application/octet-stream$LF",
        $fileEnc,
        "--$boundary--$LF" 
    ) -join $LF
    
    Invoke-RestMethod -Uri $URL -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines
    

提交回复
热议问题