Convert HttpPostedFileBase to byte[]

ArraysImageasp.net Mvc-3

Arrays Problem Overview


In my MVC application, I am using following code to upload a file.

MODEL

 public HttpPostedFileBase File { get; set; }

VIEW

@Html.TextBoxFor(m => m.File, new { type = "file" })

Everything working fine .. But I am trying to convert the result fiel to byte[] .How can i do this

CONTROLLER

 public ActionResult ManagePhotos(ManagePhotos model)
    {
        if (ModelState.IsValid)
        {
            byte[] image = model.File; //Its not working .How can convert this to byte array
        }
     }

Arrays Solutions


Solution 1 - Arrays

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

Solution 2 - Arrays

You can read it from the input stream:

public ActionResult ManagePhotos(ManagePhotos model)
{
    if (ModelState.IsValid)
    {
        byte[] image = new byte[model.File.ContentLength];
        model.File.InputStream.Read(image, 0, image.Length); 

        // TODO: Do something with the byte array here
    }
    ...
}

And if you intend to directly save the file to the disk you could use the model.File.SaveAs method. You might find the following blog post useful.

Solution 3 - Arrays

byte[] file = new byte[excelFile.ContentLength];
excelFile.InputStream.Read(file, 0, file.Length);

//Create memory stream object from your bytes
MemoryStream ms = new MemoryStream(file);

// Set WorkbookPart , Sheet
using (var myDoc = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(ms, true))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNull PointerView Question on Stackoverflow
Solution 1 - ArraysJon SkeetView Answer on Stackoverflow
Solution 2 - ArraysDarin DimitrovView Answer on Stackoverflow
Solution 3 - Arraysibadullah shaikView Answer on Stackoverflow