通过HTTPWebRequest发送文件并从$ _FILES在Web服务器上接收

时间:2014-06-11 10:28:31

标签: c# php file-upload httpwebrequest

我的.NET应用程序通过HttpWebRequest将单个简单文本文件发送到Web服务器。但是在Web服务器端,我总是得到一个空的$ _FILES数组。

我阅读了所有这些问题和文章:

这是测试代码:

public static void UploadFile()
{
    var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

    var httpRequest = (HttpWebRequest)WebRequest.Create(@"https://test.com/upload.php");
    httpRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
    httpRequest.AllowAutoRedirect = true;
    httpRequest.MaximumAutomaticRedirections = 1;
    httpRequest.Method = "POST";
    httpRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    httpRequest.KeepAlive = true;

    using (var requestStream = httpRequest.GetRequestStream())
    {
        var data = Encoding.UTF8.GetBytes("--" + boundary + "\r\n\r\n");
        requestStream.Write(data, 0, data.Length);

        data = Encoding.UTF8.GetBytes("Content-Disposition: form-data; name=\"MAX_FILE_SIZE\"\r\n\r\n");
        requestStream.Write(data, 0, data.Length);

        data = Encoding.UTF8.GetBytes("1048576"); // 1Mb
        requestStream.Write(data, 0, data.Length);

        data = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
        requestStream.Write(data, 0, data.Length);

        data = Encoding.UTF8.GetBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"upload.txt\"\r\n");
        requestStream.Write(data, 0, data.Length);

        data = Encoding.UTF8.GetBytes("Content-Type: application/octet-stream\r\n\r\n");
        requestStream.Write(data, 0, data.Length);

        data = File.ReadAllBytes(@"D:\upload.txt");
        requestStream.Write(data, 0, data.Length);

        data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--");
        requestStream.Write(data, 0, data.Length);
    }

    using (var response = (HttpWebResponse)httpRequest.GetResponse())
    using (var sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        Console.WriteLine(sr.ReadToEnd());
}

/upload.php:

exit (var_dump($_FILES));

在控制台中,输出始终为: array(0){}
请帮忙。

1 个答案:

答案 0 :(得分:0)

根据评论写出答案。

Fiddler允许您在发出请求和检索响应时检查通过线路发送的数据。它是一个代理,它是免费的(现在): - )

当遇到类似这样的问题时,必须手动使其工作,然后尝试以编程方式重新创建请求并检查请求以确定它是以正确的方式构建的。