powershell invoke-restmethod multipart/form-data

后端 未结 6 598
不思量自难忘°
不思量自难忘° 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:36

    I had some troubles trying to do the following curl command using Invoke-RestMethod:

    curl --request POST \
      --url https://example.com/upload_endpoint/ \
      --header 'content-type: multipart/form-data' \
      --form 'file=@example.csv'
      -v
    

    In my case, it turned out to be much easier to just use curl directly inside powershell.

    $FilePath = "C:\example.csv"
    $CurlExecutable = "C:\curl-7.54.1-win64-mingw\bin\curl.exe"
    
    $CurlArguments = '--request', 'POST', 
                    'https://example.com/upload_endpoint/',
                    '--header', "'content-type: multipart/form-data'",
                    '--form', "file=@$FilePath"
                    '-v',
    
    # Debug the above variables to see what's going to be executed
    Write-Host "FilePath" $FilePath
    Write-Host "CurlExecutable" $FilePath
    Write-Host "CurlArguments" $CurlArguments
    
    # Execute the curl command with its arguments
    & $CurlExecutable @CurlArguments
    

    Just grab the executable for your os on curl's website.

    Why should I use curl instead of powershell's invoke-restmethod?

    • Curl is free and open source software
    • Easy to debug and supports many operating systems.
    • Can be used in other shells as well
    • Supports multiple protocols
    • Many of the tools out there can generate curl commands
    • Supports uploading files larger than 2GB (thanks for heads up Shukri Adams)

提交回复
热议问题