[英]ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient
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. 但是,我无法弄清楚如何使用HttpClient API模拟相同的帖子。 The
FormUrlEncodedContent
bit is simple enough, but how do I add the file contents with the name to the post? FormUrlEncodedContent
位很简单,但如何将带有名称的文件内容添加到帖子中?
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;
}
}
You need to look for various subclasses of HttpContent
. 您需要查找
HttpContent
各种子类。
You create a multiform http content and add various parts to it. 您创建一个多形式的http内容并添加各种部分。 In your case you have a byte array content and form url encoded along the lines of :
在您的情况下,您有一个字节数组内容和表单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);
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.
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.