Convert HttpContent into byte[]

20,293

Solution 1

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);

Solution 2

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;

Solution 3

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 = await response.Content.ReadAsStreamAsync();
using (var memoryStream = new MemoryStream())
{
      await stream.CopyToAsync(memoryStream);
      return memoryStream.ToArray();
}
Share:
20,293
James Madison
Author by

James Madison

Updated on November 06, 2020

Comments

  • James Madison
    James Madison over 3 years

    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;
    }
    
  • James Madison
    James Madison almost 9 years
    This returns a nice long byte[], but I have two separate images I need to extract
  • James Madison
    James Madison almost 9 years
    I'm looking for an answer with a little more detail, maybe an example
  • Yuval Itzchakov
    Yuval Itzchakov almost 9 years
    @James What .NET version are you on?
  • Yuval Itzchakov
    Yuval Itzchakov almost 9 years
    Try cleaning and rebuilding.
  • James Madison
    James Madison almost 9 years
    That didn't change anything
  • Yuval Itzchakov
    Yuval Itzchakov almost 9 years
    See this
  • James Madison
    James Madison almost 9 years
    I wasn't able to get it resolved... but regardless, this doesn't fix the issue where I have two images, or two separate byte[] that I need to extract.
  • Yuval Itzchakov
    Yuval Itzchakov almost 9 years
    @JamesMadison Nowhere in your question did you say you'll be receiving a concatenated byte array. You only asked how to read a byte array from a stream.
  • James Madison
    James Madison almost 9 years
    First line of the question says I am sending two images
  • Yuval Itzchakov
    Yuval Itzchakov almost 9 years
    @James Sending two images to a server by no means says "I have one large buffer". How do you signal the end of the image? You need a delimiter.
  • VSO
    VSO over 3 years
    Great answer, but avoid using .Result, almost always, as it can cause thread locks.
  • Pavel Brun
    Pavel Brun about 3 years
    @VSO Why? Why would it cause thread locks?