0

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

4

2 回答 2

2

两个想法。首先,您似乎正在上传文件名而不是文件的内容。其次,如果您在 POST 中上传文件的内容,您可能需要使用类似[System.Web.HttpUtility]::UrlEncode(). 另外,请查看我对这个相关 SO 问题的回答

于 2013-02-14T02:30:56.220 回答
0

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

于 2013-02-14T16:52:30.883 回答