Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert HttpPostedFileBase to Byte[]

I have a controller that takes in a HttpPostedFileBase (a .jpg or .png, etc.).

public ActionResult SaveImage(HttpPostedFileBase ImageData)
{
  //code
}

ImageData becomes a System.Web.HttpPostedFileWrapper object with these properties:

ContentLength: 71945
ContentType: "image/png"
FileName: "foo.png"
InputStream: {System.Web.HttpInputStream}

I don't have any problems taking the ImageData and converting it to an Image, and then converting the Image to a byte[] and then to a base64 string - but I tried converting it directly into a byte[] with the following code:

byte[] imgData;

using (Stream inputStream = ImageData.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }

    imgData = memoryStream.ToArray();
}

memoryStream is always empty by the time imgData = memoryStream.ToArray(); is invoked, so imgData ends up being null as well.

I'm having a hard time understanding why I cannot read this InputStream into a MemoryStream. The InputStream seems seems fine, with the exception of the readTimeout and writeTimeout properties throwing timeouts are not supported on this stream. What am I doing wrong, and how come I can't convert ImageData into a byte[]?

Just in case, this is my AJAX call. Could it be an issue with the contentType or processData options being set to false?

$.ajax({
    url: 'SaveImage',
    data: formData,
    type: "POST",
    contentType: false,
    processData: false,
    beforeSend: function () {
        $("#loadingScreenModal").modal('toggle');
    },
    success: function (data) {
        // etc.
    }
});

UPDATE: I resolved the issue by converting the HttpPostedFileBase to an Image, and then converting the Image to a byte[], but I'm still interested in figuring out why I have to perform this intermediate step.

Image i = Image.FromStream(ImageData.InputStream, true, true);
byte[] imgData = imageToByteArray(thumb);

public byte[] imageToByteArray(Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

UPDATE #2: I think it probably stands to reason that the problem with my code is the code within the if (memoryStream == null) block never being invoked.

like image 323
alex Avatar asked Dec 08 '14 19:12

alex


1 Answers

You can use the BinaryReader class to read a string into a byte array:

byte[] imgData;

using (var reader = new BinaryReader(ImageData.InputStream))
{
    imgData = reader.ReadBytes(ImageData.ContentLength);
}
like image 144
D Stanley Avatar answered Sep 28 '22 01:09

D Stanley