ASP.NET WebApi:如何使用WebApi HttpClient执行带文件上载的多部分帖子

Mic*_*per 57 c# asp.net asp.net-web-api dotnet-httpclient

我有一个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>
Run Code Online (Sandbox Code Playgroud)

但是,我无法弄清楚如何使用HttpClient API模拟相同的帖子.这个FormUrlEncodedContent位很简单,但是如何将文件内容与名称一起添加到帖子中?

Mic*_*per 121

经过多次试验和错误,这里的代码实际上有效:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对大文件使用StreamContent:var fileContent = new StreamContent(File.OpenRead(fileName)); (21认同)
  • 仅供参考,System.Net.Mime.DispositionTypeNames下有"附件"常量 (6认同)
  • 奇怪的是,这对我不起作用.我不得不添加内容周围的名字报价,看到这一点:http://stackoverflow.com/questions/15638622/how-to-upload-files-to-asp-net-mvc-4-0-action-running-in -iis-EXPRESS-与-httpcl/15638623#15638623 (3认同)
  • 我也必须在名称值周围添加引号:FileName ="\"TestImage.jpg \"".我在服务器上使用ServiceStack而不是WebAPI,不确定它是否相关. (2认同)

Ali*_*tad 10

你需要寻找各种子类HttpContent.

您创建一个多形式的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);
Run Code Online (Sandbox Code Playgroud)


Thi*_*PXP 10

谢谢@Michael Tepper的回答.

我不得不将附件发布到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);
Run Code Online (Sandbox Code Playgroud)

这里供将来参考.谢谢.