How to send a file and generate data using HttpClient in C #

How can I send a file and generate data using HttpClient ?

I have two ways to submit a file or form data. But I want to submit as an HTML form. How can i do this? Thank you

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(); } 
+5
source share
1 answer

Here is the code that I use to send form information and 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 file. There is an error in the MultipartFormDataContent file .

In 4.5.1, MultipartFormDataContent wraps data with valid quotation marks.

+8
source

Source: https://habr.com/ru/post/1264180/


All Articles