Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# MultipartFormDataContent Add methods (how to properly add a file)

I'm using the MultipartFormDataContent to upload a file to a rest API. This is working well, but my questions focuses on the proper way to use the Add(...) method to include the file content. Currently I am doing such:

string fileName = "foobar.txt";
MultipartFormDataContent formContent = new MultipartFormDataContent();
ByteArrayContent byteArray = ...;
formContent.Add(byteArray, "file", fileName);
...

again, this works - I am trying to understand the parameters to the Add(...) method. In the MSDN documentation at: https://msdn.microsoft.com/en-us/library/system.net.http.multipartformdatacontent(v=vs.118).aspx

it has two add methods:

  1. Add(HttpContent, String)
  2. Add(HttpContent, String, String)

however neither has a description listed, and when drilling into the methods themselves, the parameters are only described (again without descriptions) as:

  1. HttpContent content, string name
  2. HttpContent content, string name, string fileName

so, my specific questions in this context are:

  • What is the 'name' parameter? (the one I'm setting as "file")?
  • Does this need to be the literal string "file" or can it be something else?
  • How is it used?
like image 295
russellelbert Avatar asked Feb 16 '17 15:02

russellelbert


2 Answers

It is written into the content disposition header. it looks like you can leave it off for a file upload. name looks like it corresponds to the input name.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

like image 187
Fran Avatar answered Sep 20 '22 09:09

Fran


As per the method with three parameters, following's a brief description for each param.

public void Add(HttpContent content, string name, string fileName);

content - content that needs to be sent (Ex: array, file).

name - Name for that content. This is essential if the web API has to search for a specific name.

filename - The name which'll be added to the content-disposition header of the message. This will be used by the web API to save the file.

like image 30
Brion Mario Avatar answered Sep 18 '22 09:09

Brion Mario