C# ASP.NET WebApi:如何使用 WebApi HttpClient 执行带有文件上传的多部分发布

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10339877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:27:52  来源:igfitidea点击:

ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient

c#asp.netasp.net-web-apidotnet-httpclient

提问by Michael Teper

I have a WebApi service handling an upload from a simple form, like this one:

我有一个 WebApi 服务处理来自一个简单表单的上传,如下所示:

    <form action="/api/workitems" enctype="multipart/form-data" method="post">
        <input type="hidden" name="type" value="ExtractText" />
        <input type="file" name="FileForUpload" />
        <input type="submit" value="Run test" />
    </form>

However, I can't figure out how to simulate the same post using the HttpClient API. The FormUrlEncodedContentbit is simple enough, but how do I add the file contents with the name to the post?

但是,我不知道如何使用 HttpClient API 模拟相同的帖子。这FormUrlEncodedContent一点很简单,但是如何将带有名称的文件内容添加到帖子中?

采纳答案by Michael Teper

After much trial and error, here's code that actually works:

经过多次反复试验,以下是实际有效的代码:

using (var client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        var values = new[]
        {
            new KeyValuePair<string, string>("Foo", "Bar"),
            new KeyValuePair<string, string>("More", "Less"),
        };

        foreach (var keyValuePair in values)
        {
            content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
        }

        var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "Foo.txt"
        };
        content.Add(fileContent);

        var requestUri = "/api/action";
        var result = client.PostAsync(requestUri, content).Result;
    }
}

回答by Aliostad

You need to look for various subclasses of HttpContent.

您需要寻找HttpContent.

You create a multiform http content and add various parts to it. In your case you have a byte array content and form url encoded along the lines of:

您创建了一个多形式的 http 内容并向其中添加了各个部分。在您的情况下,您有一个字节数组内容和表单 url沿以下行编码:

HttpClient c = new HttpClient();
var fileContent = new ByteArrayContent(new byte[100]);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                                            {
                                                FileName = "myFilename.txt"
                                            };

var formData = new FormUrlEncodedContent(new[]
                                            {
                                                new KeyValuePair<string, string>("name", "ali"),
                                                new KeyValuePair<string, string>("title", "ostad")
                                            });


MultipartContent content = new MultipartContent();
content.Add(formData);
content.Add(fileContent);
c.PostAsync(myUrl, content);

回答by ThiagoPXP

Thank you @Michael Tepper for your answer.

谢谢@Michael Tepper 的回答。

I had to post attachments to MailGun (email provider) and I had to modify it slightly so it would accept my attachments.

我不得不将附件发布到 MailGun(电子邮件提供商),我不得不稍微修改它以便它接受我的附件。

var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
fileContent.Headers.ContentDisposition = 
        new ContentDispositionHeaderValue("form-data") //<- 'form-data' instead of 'attachment'
{
    Name = "attachment", // <- included line...
    FileName = "Foo.txt",
};
multipartFormDataContent.Add(fileContent);

Here for future reference. Thanks.

此处供日后参考。谢谢。