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

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

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

    

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?

回答1:

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("Foo", "Bar"),             new KeyValuePair("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;     } } 


回答2:

You need to look for various subclasses of 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:

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("name", "ali"),                                                 new KeyValuePair("title", "ostad")                                             });   MultipartContent content = new MultipartContent(); content.Add(formData); content.Add(fileContent); c.PostAsync(myUrl, content); 


回答3:

Thank you @Michael Tepper for your answer.

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

var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName)); fileContent.Headers.ContentDisposition =          new ContentDispositionHeaderValue("form-data") //

Here for future reference. Thanks.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!