Search code examples
c#wcfweb-servicesrestfiddler

Upload multiple files in a single HTTPWebRequest


I have created a service which accept 2 things :

1) A body parameter called "type".

2) A csv file to be uploaded.

i am reading this two things in server side like this:

 //Read body params
 string type = HttpContext.Current.Request.Form["type"];

 //read uploaded csv file
 Stream csvStream = HttpContext.Current.Request.Files[0].InputStream;

how can i test this, i am using Fiddler to test this but i can send only one thing at a time(either type or file), because both things are of different content type, how can i use content type multipart/form-data and application/x-www-form-urlencoded at same time.

Even i use this code

    public static void PostDataCSV()
    {
        //open the sample csv file
        byte[] fileToSend = File.ReadAllBytes(@"C:\SampleData.csv"); 

        string url = "http://localhost/upload.xml";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "multipart/form-data";
        request.ContentLength = fileToSend.Length;


        using (Stream requestStream = request.GetRequestStream())
        {
            // Send the file as body request. 
            requestStream.Write(fileToSend, 0, fileToSend.Length);
            requestStream.Close();
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        //read the response
        string result;
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            result = reader.ReadToEnd();
        }

        Console.WriteLine(result);
    }

This also not sending any file to server.


Solution

  • The code you have above does not create a proper multipart body.

    You can't simply write the file into the stream, each part requires a preamble boundary marker with per-part headers, etc.

    See Upload files with HTTPWebrequest (multipart/form-data)