2008-12-11 108 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();