2008-12-11 113 views
129

我正在使用具有FromBinary方法的图像组件。想知道如何将我的输入流中的字节数组如何从HttpPostedFile创建字节数组

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

ImageElement image = ImageElement.FromBinary(byteArray); 
+0

我们如何发布文件中的另一个.aspx页面中? – shivi 2015-06-23 01:42:17

+0

不是这行** file.InputStream.Read(buffer,0,file.ContentLength); **用输入流中的字节填充缓冲区?为什么我们应该使用** BinaryReader.ReadBytes(...)**作为@Wolfwyrd在下面的答案中提到的?不会** ImageElement.FromBinary(缓冲区); **解决问题? – 2017-06-20 06:00:45

回答

244

使用BinaryReader在对象从像流返回一个字节数组:

byte[] fileData = null; 
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream)) 
{ 
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength); 
} 
+1

正如jeff所述, b.ReadBytes(file.InputStream.Length);应该是 byte [] binData = b.ReadBytes(file.ContentLength); as .Length很长,而ReadBytes需要一个int。 – Spongeboy 2009-12-17 04:13:39

3
在你的问题

,既缓冲和ByteArray似乎成为byte []。所以:

ImageElement image = ImageElement.FromBinary(buffer); 
20
BinaryReader b = new BinaryReader(file.InputStream); 
byte[] binData = b.ReadBytes(file.InputStream.Length); 

2号线应与

byte[] binData = b.ReadBytes(file.ContentLength); 
10

被替换,如果你的文件InputStream.Position被设定为数据流的末尾它不会工作。 我的其他行:

Stream stream = file.InputStream; 
stream.Position = 0; 
2

stream.copyto之前,必须重置stream.position为0;然后 它工作正常。

2

对于影像时,如果您使用Web页v2使用 WebImage Class

var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream); 
byte[] imgByteArray = webImage.GetBytes();