Convert HttpContent to Byte []

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.

  • How to extract Image or byte[] from an HttpContent object?
  • 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; } 
+6
source share
4 answers
 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); 
+1
source

HttpContent has an Async method that returns ByteArray ie (Task ByteArray)

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

You can run the method synchronously

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

Take a look at the CopyToAsync (Stream, TransportContext) method opened by the ByteArrayContent class. [msdn link]

0
source

You can use HttpContent.ReadAsByteArrayAsync :

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

Or you can read the contents using HttpContent.ReadAsStreamAsync and extract byte[] from it:

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

Source: https://habr.com/ru/post/990050/


All Articles