[英]Unable to upload file using HTTP POST
我正在尝试使用HTTP Post上传文件,但是以某种方式在服务器端处理请求时找不到文件。 我能够创建一个类似的请求,并使用Chrome的Postman扩展程序成功上传文件,但是以某种方式无法以编程方式进行相同的操作。
客户代码:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUrl);
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
{
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
string header = string.Format(headerTemplate, "Files", "myFile.xml", "text/xml");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
requestStream.Write(headerbytes, 0, headerbytes.Length);
requestStream.Write(uploadedFile, 0, uploadedFile.Length);
requestStream.Write(trailer, 0, trailer.Length);
}
请求看起来像这样(在Fiddler中):
POST https://host/myUrl
Content-Length: 1067
Expect: 100-continue
Connection: Keep-Alive
------------8d2942f79ab208e
Content-Disposition: form-data; name="Files"; filename="myFile.xml"
Content-Type:text/xml
<myFile>
Something
</myFile>
------------8d2942f79ab208e
服务器端:
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count != 1)
return BadRequest("Didn't get the file.");
但是我总是将httpRequest.Files.Count
设为零。 为什么?
以下请求(使用Postman创建)使我的httpRequest.Files.Count
为1,这与预期的一样。
POST myUrl HTTP/1.1
Host: host
Cache-Control: no-cache
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="Files"; filename="myFile.xml"
Content-Type: text/xml
----WebKitFormBoundaryE19zNvXGzXaLvS5C
我究竟做错了什么?
弄清楚了。 感谢这个博客
进行了两项更改:
1)添加了ContentType:
request.ContentType = "multipart/form-data; boundary=" + boundary;
2)修改边界的结束方式
byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--");
现在就可以了。 希望这对某人有帮助。
也许您需要将请求的内容类型设置为“ multipart / form-data”
request.ContentType = "multipart/form-data";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.