Convert HttpContent into byte[]

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I am currently working on a c# web API. For a specific call I need to send 2 images using an ajax call to the API, so that the API can save them as varbinary(max) in the database.

  1. How do you extract an Image or byte[] from a HttpContent object?
  2. How do I do this twice? Once for each image.

-

var authToken = $("#AuthToken").val(); var formData = new FormData($('form')[0]); debugger; $.ajax({     url: "/api/obj/Create/",      headers: { "Authorization-Token": authToken },     type: 'POST',     xhr: function () {          var myXhr = $.ajaxSettings.xhr();         return myXhr;     },     data: formData,     cache: false,     contentType: false,     processData: false }); 

-

public async Task<int> Create(HttpContent content) {     if (!content.IsMimeMultipartContent())     {         throw new UnsupportedMediaTypeException("MIME Multipart Content is not supported");     }      return 3; } 

回答1:

HttpContent has a Async method which return ByteArray i.e (Task of ByteArray)

 Byte[] byteArray = await Content.ReadAsByteArrayAsync(); 

You can run the method synchronously

Byte[] byteArray = Content.ReadAsByteArrayAsync().Result; 


回答2:

if (!content.IsMimeMultipartContent()) {     throw new UnsupportedMediaTypeException("MIME Multipart Content is not supported"); }  var uploadPath = **whatever**; if (!Directory.Exists(uploadPath)) {     Directory.CreateDirectory(uploadPath); }  var provider = new MultipartFormDataStreamProvider(uploadPath); await content.ReadAsMultipartAsync(provider);  return File.ReadAllBytes(provider.FileData[0].LocalFileName); 


回答3:

Please look at CopyToAsync(Stream, TransportContext) method exposed by ByteArrayContent Class. [msdn link]



回答4:

You can use HttpContent.ReadAsByteArrayAsync:

byte[] bytes = await response.Content.ReadAsByteArrayAsync(); 

Or, you can read the content with HttpContent.ReadAsStreamAsync and extract to a byte[] from there:

var stream = response.Content.ReadAsStreamAsync(); using (var memoryStream = new MemoryStream()) {       await stream.CopyToAsync(stream);       return memoryStream.ToArray(); } 


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