如何在C#中使用HttpClient发送文件和表单数据 [英] How to send a file and form data with HttpClient in C#

查看:1195
本文介绍了如何在C#中使用HttpClient发送文件和表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 HttpClient 发送文件和表单数据?

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

我有两种发送方式文件或表单数据。但我想像HTML表单一样发送两者。我怎样才能做到这一点?谢谢。

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.

这是我的代码:

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();
}


推荐答案

这是我正在使用的代码发布表单信息和一个csv文件

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;
}

这是.net 4.5版本。

This is for .net 4.5.

请注意MultipartFormDataContent中的\。其中有一个

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

在4.5.1中,MultipartFormDataContent中的multipartformdatacontent-should-quote-name-field-of-content-disposition rel = noreferrer> bug

In 4.5.1 MultipartFormDataContent wraps the data with the correct quotes.

更新:自从Microsoft Connect退出后,此错误的链接不再起作用。

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

这篇关于如何在C#中使用HttpClient发送文件和表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆