【发布时间】:2014-08-01 08:57:58
【问题描述】:
我的 .NET 应用程序通过 HttpWebRequest 向网络服务器发送一个简单的文本文件。但是在网络服务器端,我总是得到一个空的 $_FILES 数组。
我阅读了所有这些问题和文章:
- POSTING MULTIPART/FORM-DATA USING .NET WEBREQUEST
- Upload files with HTTPWebrequest (multipart/form-data)
- How to recieve POST data sent using “application/octet-stream” in PHP?
- and PHP manual of course: Handling file uploads
这里是测试代码:
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){}
请帮忙。
【问题讨论】:
-
你检查过fiddler的请求和响应了吗?尝试手动上传一个或多个文件,然后尝试使用
HttpWebRequest重新创建请求。 -
感谢您的建议。我现在去看看。
-
它解决了这个问题。非常感谢! Fiddler 向我显示请求正文不正确。我编辑了我的代码,现在一切正常:)。
-
太棒了,我很高兴听到你让它工作了 :-)
标签: c# php file-upload httpwebrequest