How to send a file and form data with HttpClient in C#

前端 未结 2 541
滥情空心
滥情空心 2020-11-30 12:44

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

2条回答
  •  悲哀的现实
    2020-11-30 13:03

    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.

提交回复
热议问题