简体   繁体   English

如何从HttpPostedFile创建字节数组

[英]How to create byte array from HttpPostedFile

I'm using an image component that has a FromBinary method. 我正在使用具有FromBinary方法的图像组件。 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);

Use a BinaryReader object to return a byte array from the stream like: 使用BinaryReader对象从流中返回字节数组,如:

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);

line 2 should be replaced with 第2行应替换为

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

It won't work if your file InputStream.Position is set to the end of the stream. 如果您的文件InputStream.Position设置为流的末尾,它将无法工作。 My additional lines: 我的其他内容:

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

in your question, both buffer and byteArray seem to be byte[]. 在你的问题中,缓冲区和byteArray似乎都是byte []。 So: 所以:

ImageElement image = ImageElement.FromBinary(buffer);

before stream.copyto, you must reset stream.position to 0; 在stream.copyto之前,必须将stream.position重置为0; then it works fine. 然后它工作正常。

For images if your using Web Pages v2 use the WebImage Class 对于使用Web页面v2使用WebImage类的图像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM