Powershell HTTP POST File Upload for REST api

2019-08-23 05:01发布

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();
        }
    }

2条回答
萌系小妹纸
2楼-- · 2019-08-23 05:31

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.

查看更多
Animai°情兽
3楼-- · 2019-08-23 05:51

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.

查看更多
登录 后发表回答