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

本文关键字:接收 FILES 服务器 web HTTPWebRequest 文件 通过 | 更新日期: 2023-09-27 18:08:02

我的。net应用程序通过HttpWebRequest向web-server发送一个简单的文本文件。但是在web服务器端,我总是得到一个空$_FILES数组。

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

  • 使用。net webrequest发布多部分/表单数据
  • 使用HTTPWebrequest (multipart/form-data)上传文件
  • 如何接收POST数据发送使用" application/octet-stream "在PHP?
  • 和PHP手册当然:处理文件上传
下面是测试代码:
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){}
请帮助。

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

根据评论写一个答案

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

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