0

I am trying send a csv file and parameters to a http API and am struggling to debug what is going wrong.

For POST requests that require parameters only (no csv file) then I can successfully do this:

    HttpContent upload = new FormUrlEncodedContent(new Dictionary<string, string> { { "name", "myName" }});
    HttpResponseMessage uploadResponse = await client.PostAsync("api/datasets", upload);

For POST requests that require parameters and a csv file I am using MultipartFormDataContent:

            var content = new MultipartFormDataContent();

            HttpContent upload = new FormUrlEncodedContent(new Dictionary<string, string> { { "name", "myName" }});            
            content.Add(upload);

            byte[] csvBytes = File.ReadAllBytes("myfile.csv");
            var csvContent = new ByteArrayContent(csvBytes);
            content.Add(csvContent, "csvfile", "datafile.csv");

            HttpResponseMessage uploadResponse = await client.PostAsync("api/datasets", content);

However, the sever is now returning a message saying I have not specified the "name" parameter. What am I missing? How do I submit the parameters correctly?

Cameron
  • 229
  • 1
  • 5
  • 17

3 Answers3

1

before content.Add(csvContent, "csvfile", "datafile.csv"); add these lines:

csvContent.Headers.Add("Content-Type", "text/csv");
csvContent.Headers.Add("Content-Disposition", "form-data; name=\"csvfile\"; filename=\"datafile.csv\"");
Omid.Hanjani
  • 1,444
  • 2
  • 20
  • 29
0

change to this

new Dictionary<string, string> { { "name", "myName" }}

to

new List<KeyValuePair<string, string>>({ "name", "myName" })

it should notice the param now.

Webmaster
  • 1
  • 1
0

Here's my guess:

To wrap up a series of key/value pairs, you should choose either application/x-www-form-urlencoded (FormUrlEncodedContent) or multipart/form-data (MultipartFormDataContent). If you use both then you're creating two levels of boxes.

Specifically, the API you're calling almost certainly wants

  multipart/form-data
    subpart with name "parameter1" value "value1"
    subpart with name "parameter2" value "value2"
    subpart with name "csvfile" value <contents of datafile.csv>

but you're giving it

  multipart/form-data
    subpart with no name, value "parameter1=value1&parameter2=value2", content-type x-www-form-urlencoded
    subpart with name "csvfile" value <contents of datafile.csv>

See What does enctype='multipart/form-data' mean? for a more complete explanation of the two ways of returning form data.

Paul Du Bois
  • 2,097
  • 1
  • 20
  • 31