How to send multipart/form-data with PowerShell Invoke-RestMethod

后端 未结 3 1672
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 13:18

I\'m trying to send a file via Invoke-RestMethod in a similar context as curl with the -F switch.

Curl Example

curl -F FileName=@\"/path-to-file.na         


        
相关标签:
3条回答
  • 2020-11-28 13:58

    The problem here was what the API required some additional parameters. Initial request required some parameters to accept raw content and specify filename/size. After setting that and getting back proper link to submit, I was able to use:

    Invoke-RestMethod -Uri $uri -Method Post -InFile $filePath -ContentType "multipart/form-data"
    
    0 讨论(0)
  • 2020-11-28 14:00

    The accepted answer won't do a multipart/form-data request, but rather a application/x-www-form-urlencoded request forcing the Content-Type header to a value that the body does not contain.

    One way to send a multipart/form-data formatted request with PowerShell is:

    $ErrorActionPreference = 'Stop'
    
    $fieldName = 'file'
    $filePath = 'C:\Temp\test.pdf'
    $url = 'http://posttestserver.com/post.php'
    
    Try {
        Add-Type -AssemblyName 'System.Net.Http'
    
        $client = New-Object System.Net.Http.HttpClient
        $content = New-Object System.Net.Http.MultipartFormDataContent
        $fileStream = [System.IO.File]::OpenRead($filePath)
        $fileName = [System.IO.Path]::GetFileName($filePath)
        $fileContent = New-Object System.Net.Http.StreamContent($fileStream)
        $content.Add($fileContent, $fieldName, $fileName)
    
        $result = $client.PostAsync($url, $content).Result
        $result.EnsureSuccessStatusCode()
    }
    Catch {
        Write-Error $_
        exit 1
    }
    Finally {
        if ($client -ne $null) { $client.Dispose() }
        if ($content -ne $null) { $content.Dispose() }
        if ($fileStream -ne $null) { $fileStream.Dispose() }
        if ($fileContent -ne $null) { $fileContent.Dispose() }
    }
    
    0 讨论(0)
  • 2020-11-28 14:03

    I found this post and changed it a bit

    $fileName = "..."
    $uri = "..."
    
    $currentPath = Convert-Path .
    $filePath="$currentPath\$fileName"
    
    $fileBin = [System.IO.File]::ReadAlltext($filePath)
    $boundary = [System.Guid]::NewGuid().ToString()
    $LF = "`r`n"
    $bodyLines = (
        "--$boundary",
        "Content-Disposition: form-data; name=`"file`"; filename=`"$fileName`"",
        "Content-Type: application/octet-stream$LF",
        $fileBin,
        "--$boundary--$LF"
    ) -join $LF
    
    Invoke-RestMethod -Uri $uri -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines
    
    0 讨论(0)
提交回复
热议问题