[英]ASP.NET WebApi: how to perform a multipart post with file upload using WebApi 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>
但是,我無法弄清楚如何使用HttpClient API模擬相同的帖子。 FormUrlEncodedContent
位很簡單,但如何將帶有名稱的文件內容添加到帖子中?
經過多次試驗和錯誤,這里的代碼實際上有效:
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;
}
}
您需要查找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);
謝謝@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);
這里供將來參考。 謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.