Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 250
CodeGuru Avatar asked Feb 26 '13 10:02

CodeGuru


People also ask

How do I upload multiple files to .NET core?

Uploading Multiple files in ASP.NET Core MVC To Upload multiple files, navigate to " HomeController. cs " and now in the arguments we will take multiple files using "List<IFormFile>" and we will loop through each file to save it on physical drive.

How does multipart file upload work?

Multipart upload allows you to upload a single object as a set of parts. Each part is a contiguous portion of the object's data. You can upload these object parts independently and in any order. If transmission of any part fails, you can retransmit that part without affecting other parts.


1 Answers

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)

like image 184
EricLaw Avatar answered Nov 06 '22 21:11

EricLaw