无法使用HTTP POST上传文件

时间:2015-07-24 20:15:34

标签: c# 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成为一个,正如预期的那样。

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

我做错了什么?

2 个答案:

答案 0 :(得分:3)

想出来。感谢blog

做了两处修改:

1)添加了ContentType:

   request.ContentType = "multipart/form-data; boundary=" + boundary;

2)修改了边界的结束

byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--");

它现在有效。希望这有助于某人。

答案 1 :(得分:0)

也许您需要将请求的内容类型设置为“multipart / form-data”

request.ContentType = "multipart/form-data";