How to create byte array from HttpPostedFile
Asked Answered
T

6

165

I'm using an image component that has a FromBinary method. Wondering how do I convert my input stream into a byte array

HttpPostedFile file = context.Request.Files[0];
byte[] buffer = new byte[file.ContentLength];
file.InputStream.Read(buffer, 0, file.ContentLength);

ImageElement image = ImageElement.FromBinary(byteArray);
Tirrell answered 11/12, 2008 at 16:13 Comment(2)
how are we posting the file in another .aspx page?Lucid
Doesn't this line file.InputStream.Read(buffer, 0, file.ContentLength); fill the buffer with bytes from the input stream? Why should we use BinaryReader.ReadBytes(...) as mentioned by @Wolfwyrd in the answer below? Won't ImageElement.FromBinary(buffer); fix the problem?Bridge
S
310

Use a BinaryReader object to return a byte array from the stream like:

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
Spanish answered 11/12, 2008 at 16:32 Comment(4)
As mentioned below by jeff, b.ReadBytes(file.InputStream.Length); should be byte[] binData = b.ReadBytes(file.ContentLength); as .Length is a long whereas ReadBytes expects an int.Gleet
Remember to close the BinaryReader.Responser
Binary reader doesn't have to be closed, because there is a using that is automaticaly closing the reader on disposalFit
Any idea on why this wouldn't work for a .docx file? #19233432Mosasaur
I
28
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);

line 2 should be replaced with

byte[] binData = b.ReadBytes(file.ContentLength);
Instantly answered 18/3, 2009 at 17:11 Comment(0)
L
15

It won't work if your file InputStream.Position is set to the end of the stream. My additional lines:

Stream stream = file.InputStream;
stream.Position = 0;
Leavis answered 10/12, 2012 at 17:20 Comment(0)
H
3

in your question, both buffer and byteArray seem to be byte[]. So:

ImageElement image = ImageElement.FromBinary(buffer);
Hulburt answered 11/12, 2008 at 16:36 Comment(0)
J
2

before stream.copyto, you must reset stream.position to 0; then it works fine.

Jahdal answered 23/1, 2014 at 7:29 Comment(0)
S
2

For images if your using Web Pages v2 use the WebImage Class

var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream);
byte[] imgByteArray = webImage.GetBytes();
Skinhead answered 13/5, 2016 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.