2

I'm trying to upload a file using HTTP Post but somehow there is no file to be found when I process the request on the server side. I was able to create a similar request and successfully upload file using Chrome's Postman extension, but somehow can't do the same programmatically.

Client code:

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);

}     

The request looks like this (in 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

Server side:

        var httpRequest = HttpContext.Current.Request;
        if (httpRequest.Files.Count != 1)
            return BadRequest("Didn't get the file.");

But I always get httpRequest.Files.Count to be zero. Why?

The following request (created using Postman) gives me httpRequest.Files.Count to be one, as expected.

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

What am I doing wrong?

2 Answers 2

3

Figured it out. Thanks to this blog

Made two changes:

1) Added ContentType :

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

2) Modified how the boundary ends

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

And it works now. Hope this helps someone.

Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps you need to set the request's content type to "multipart/form-data"

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

2 Comments

Tried that but it did not help.
perhaps look into using WebClient.UploadFile and see if it'll work with your requirement

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.