Powershell HTTP POST File Upload for REST api

2019-08-23 05:26发布

问题:

I am new to Powershell and having trouble sending a file via an HTTP POST request. Everything is working perfectly except for sending/uploading the file. Is this possible using my existing code?

Here is my code:



    # VARIABLES
    $myFile = "c:\sample_file.csv"
    $updateUrl = "http://www.example.com/processor"
    $postData  =  "field1=value1"
    $postData += "&field2=value2"
    $postData += "&myFile=" + $myFile

    # EXECUTE FUNCTION
    updateServer -url $updateUrl -data $postData



    function updateServer {
        param(
            [string]$url = $null,
            [string]$data = $null,
            [System.Net.NetworkCredential]$credentials = $null,
            [string]$contentType = "application/x-www-form-urlencoded",
            [string]$codePageName = "UTF-8",
            [string]$userAgent = $null
        );

        if ( $url -and $data ){
            [System.Net.WebRequest]$webRequest = [System.Net.WebRequest]::Create($url);
            $webRequest.ServicePoint.Expect100Continue = $false;
            if ( $credentials ){
                $webRequest.Credentials = $credentials;
                $webRequest.PreAuthenticate = $true;
            }
            $webRequest.ContentType = $contentType;
            $webRequest.Method = "POST";
            if ( $userAgent ){
                $webRequest.UserAgent = $userAgent;
            }

            $enc = [System.Text.Encoding]::GetEncoding($codePageName);
            [byte[]]$bytes = $enc.GetBytes($data);
            $webRequest.ContentLength = $bytes.Length;
            [System.IO.Stream]$reqStream = $webRequest.GetRequestStream();
            $reqStream.Write($bytes, 0, $bytes.Length);
            $reqStream.Flush();

            $resp = $webRequest.GetResponse();
            $rs = $resp.GetResponseStream();
            [System.IO.StreamReader]$sr = New-Object System.IO.StreamReader -argumentList $rs;
            $sr.ReadToEnd();
        }
    }

回答1:

Two thoughts. First it seems you're uploading the filename but not the file's contents. Second, if you upload the file's contents within the POST you're likely going to need to URL encode the data using something like [System.Web.HttpUtility]::UrlEncode(). Also, check out my answer to this related SO question.



回答2:

I found the solution to this problem here. I think I may have come across this when I was building my script originally or a snippet of it somewhere else as it is nearly identical to what I have except more thorough.