ASP.NET WebApi:如何使用 WebApi HttpClient 执行带有文件上传的多部分发布 [英] ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient

查看:21
本文介绍了ASP.NET WebApi:如何使用 WebApi HttpClient 执行带有文件上传的多部分发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

推荐答案

经过多次尝试和错误,以下是实际可行的代码:

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

这篇关于ASP.NET WebApi:如何使用 WebApi HttpClient 执行带有文件上传的多部分发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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