6

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.

EricLaw
  • 56,563
  • 7
  • 151
  • 196
CodeGuru
  • 2,722
  • 6
  • 36
  • 52
  • 2
    **multipart** /form-data already is a header for **multiple** content types (files and form data). You should not need application/x-www-form-urlencoded with it – Fabian Schmengler Feb 26 '13 at 10:48
  • but it is not working for me, in server side i am not getting any file or you can say stream. – CodeGuru Feb 26 '13 at 10:53

2 Answers2

3

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)

Community
  • 1
  • 1
EricLaw
  • 56,563
  • 7
  • 151
  • 196
0

Some informations about your multiple contentTypes problem here : http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.2

multipart/form-data is the only way to send multiples data types over http protocol.

Digix
  • 64
  • 4