用于REST API的Powershell HTTP POST文件上载

时间:2013-02-13 18:54:16

标签: api rest post powershell

我是Powershell的新手,无法通过HTTP POST请求发送文件。除了发送/上传文件外,一切都很完美。这可以使用我现有的代码吗?

这是我的代码:



    # 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 个答案:

答案 0 :(得分:2)

两个想法。首先,它似乎是上传文件名而不是文件的内容。其次,如果您在POST中上传文件的内容,则可能需要使用[System.Web.HttpUtility]::UrlEncode()等内容对数据进行URL编码。另外,请查看我的answer to this related SO question

答案 1 :(得分:0)

我找到了解决此问题的方法here。我想我可能在最初构建我的脚本或其他地方的片段时遇到过这个问题,因为除了更彻底之外,它几乎与我所拥有的相同。