32

How can I send a file and form data with the HttpClient?

I have two ways to send a file or form data. But I want to send both like an HTML form. How can I do that? Thanks.

This is my code:

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    var client = new HttpClient();
    var requestContent = new MultipartFormDataContent();
    filename = openFileDialog1.FileName;
    array = File.ReadAllBytes(filename);
    var imageContent = new ByteArrayContent(array);
    imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("audio/*");
    requestContent.Add(imageContent, "audio", "audio.wav");
    var values = new Dictionary<string, string>
    {
        { "token", "b53b99534a137a71513548091271c44c" },
    };
    var content = new FormUrlEncodedContent(values);
    requestContent.Add(content);
    var response = await client.PostAsync("localhost", requestContent);
    var responseString = await response.Content.ReadAsStringAsync();
    txtbox.Text = responseString.ToString();
}
johnny 5
  • 19,893
  • 50
  • 121
  • 195
user2254798
  • 553
  • 2
  • 6
  • 17

2 Answers2

42

Here's code I'm using to post form information and a csv file

using (var httpClient = new HttpClient())
{
    var surveyBytes = ConvertToByteArray(surveyResponse);

    httpClient.DefaultRequestHeaders.Add("X-API-TOKEN", _apiToken);
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var byteArrayContent =   new ByteArrayContent(surveyBytes);
    byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");

    var response = await httpClient.PostAsync(_importUrl, new MultipartFormDataContent
    {
        {new StringContent(surveyId), "\"surveyId\""},
        {byteArrayContent, "\"file\"", "\"feedback.csv\""}
    });

    return response;
}

This is for .net 4.5.

Note the \" in the MultipartFormDataContent. There is a bug in MultipartFormDataContent.

In 4.5.1 MultipartFormDataContent wraps the data with the correct quotes.

Update: This link to the bug no longer works since the have retired Microsoft Connect.

johnny 5
  • 19,893
  • 50
  • 121
  • 195
Fran
  • 6,440
  • 1
  • 23
  • 35
  • thanks .i'm noob in c# but Can you help me solve the problem? – user2254798 Feb 13 '17 at 20:27
  • 1
    i gave you a working example of how to post using MultipartFormDataContent. I don't know the requirements for the site you are trying to post to. is the token supposed to be in the body or the header? what types does the site you are posting to expecting? – Fran Feb 13 '17 at 20:30
  • 1
    if this does not answer your question, please add more information what exactly your are trying to achieve. – Cee McSharpface Feb 13 '17 at 20:30
  • web service get token and file sound . give me back json . – user2254798 Feb 13 '17 at 20:37
  • Thanks! This also applies to Xamarin as of Xamarin 7.4, which is stuck in .NET Framework 4.5. I wonder if using .NET Standard 1.6 / 2.0 / ... will solve this issue? – Hendy Irawan Aug 24 '17 at 17:22
4

Here's code I'm using a method to send file and data from console to API

               
static async Task uploaddocAsync()
{
    MultipartFormDataContent form = new MultipartFormDataContent();
    Dictionary<string, string> parameters = new Dictionary<string, string>();
    //parameters.Add("username", user.Username);
    //parameters.Add("FullName", FullName);
    HttpContent DictionaryItems = new FormUrlEncodedContent(parameters);
    form.Add(DictionaryItems, "model");

    try
    {
        var stream = new FileStream(@"D:\10th.jpeg", FileMode.Open);
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(@"http:\\xyz.in");
            
        HttpContent content = new StringContent("");
        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "uploadedFile1",
            FileName = "uploadedFile1"
        };
        content = new StreamContent(stream);
        form.Add(content, "uploadedFile1"); 

        client.DefaultRequestHeaders.Add("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.dsfdsfdsfdsfsdfkhjhjkhjk.vD056hXETFMXYxOaLZRwV7Ny1vj-tZySAWq6oybBr2w");
                 
        var response = client.PostAsync(@"\api\UploadDocuments\", form).Result;
        var k = response.Content.ReadAsStringAsync().Result;
    }
    catch (Exception ex)
    {


    }
}
John
  • 321
  • 2
  • 12
Rajesh Kumar
  • 602
  • 6
  • 20
  • 3
    Does `content = new StreamContent...` not override the changes made on the line above? – JB_ Sep 16 '21 at 05:42