2

I want to send .csv file in a POST request where content type is "multipart/form-data" and in the body there is some key and the .csv file Below is the code I have tried:

string url = "*****URL*****";
string root = AppDomain.CurrentDomain.BaseDirectory;
string file = root + "Folder\\file.csv";
FileInfo fileInfo = new FileInfo(file);
int fileLength = (int)fileInfo.Length;
FileStream rdr = new FileStream(file, FileMode.Open);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);    
request.Method = "POST";
request.ContentType = "multipart/form-data";
request.Headers["Content-Type"] = "multipart/form-data";

int bytesRead = 0;
byte[] requestByte = new byte[fileLength];
request.ContentLength = requestByte.Length;

using (Stream requestStream = request.GetRequestStream())
{
    while ((bytesRead = rdr.Read(requestByte, 0, requestByte.Length)) != 0)
    {
         requestStream.Write(requestByte, 0, bytesRead);
         requestStream.Close();
    }
}

string responseData;
using (StreamReader responseStream = new StreamReader(request.GetResponse().GetResponseStream()))
{
    responseData = responseStream.ReadToEnd();
    responseStream.Close();
}

But this is giving error in the content type, may be I am doing it wrong. Please help me out here.

Indranil
  • 2,229
  • 2
  • 27
  • 40
  • 1
    Check the selected answer in this topic: http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data – Ali Bahrami Nov 29 '16 at 06:54
  • The selected answer was helpful; but, they have used NameValueCollection to send the file data. Where i have a .csv file which contains five fields. So, how should i read the data from the file and use it in the request? – Indranil Nov 29 '16 at 12:55
  • Doesn't matter. As I understand you wanted to upload a `CSV` file to server, am I correct? Just follow their workaround and use `NameValueCollecttion` to send your file. – Ali Bahrami Nov 29 '16 at 12:57

3 Answers3

0

Finally this code worked for me,

string boundary = "---" + DateTime.Now.Ticks.ToString("x");
var client = new RestClient("*****URL*****");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "multipart/form-data; boundary=" + boundary);
request.AddParameter("multipart/form-data; boundary=" + boundary, "--"+ boundary + "\r\nContent-Disposition: form-data; name=\"**KEY**\"; filename=\"***File Name***.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n--" + boundary + "--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Indranil
  • 2,229
  • 2
  • 27
  • 40
  • You seriously ask a question and than answere it by your self in two diffrent posts??? Where one is buggy as hell an the other is just a snippit ? – Dwza Sep 21 '17 at 09:27
  • Sorry, Mr. Dwza. Earlier, I didn't do much research on internet and asked the question. Later i found the solution for my question, so i answered it. And moreover, both the code worked for me. – Indranil Sep 21 '17 at 12:43
  • but the accepted code cant work. you use `boundary`, `nameValue` that never gets set. May in your other post... but not in the accepted one... and `rand` is never used. And so on ^^ – Dwza Sep 21 '17 at 13:26
0

This is a better approach:

main()
{
    HttpWebRequest request;
    HttpWebResponse response = null;
    string url = "*****URL*****";
    string path = @"..\test.csv";
    Random rand = new Random();
    string contentType = "text/csv";
    byte[] header = RequestHeader(boundary,path,nameValue, contentType);
    request = (HttpWebRequest)WebRequest.Create(url);
    RequestParameters(header, path, boundary);
    response = (HttpWebResponse)request.GetResponse();
}
private byte[] RequestHeader(string boundary, string path, string nameValue, string contentType)
{
    return System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + nameValue + "\"; filename=\"" + System.IO.Path.GetFileName(path) + "\"\r\nContent-Type:" + contentType + "\r\n\r\n");
}
private void RequestParameters(byte[] header, string path, string boundary)
{
    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
    request.Method = "post";
    request.KeepAlive = true;
    request.ContentType = "multipart/form-data" + boundary;
    data_stream = request.GetRequestStream();
    data_stream.Write(header, 0, header.Length);
    byte[] file_bytes = System.IO.File.ReadAllBytes(path);
    data_stream.Write(file_bytes, 0, file_bytes.Length);
    data_stream.Write(trailer, 0, trailer.Length);
    data_stream.Close();
}
Indranil
  • 2,229
  • 2
  • 27
  • 40
  • You really have a lot errors in this code. You may should correct them before accepting your own answere! – Dwza Sep 21 '17 at 09:24
0

I wrote a multipart form helper that does this using webclient.

feroze
  • 7,380
  • 7
  • 40
  • 57