如何从 HttpPostedFile 创建字节数组

我正在使用一个具有 FromBinary 方法的图像组件。想知道如何将输入流转换为字节数组

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


ImageElement image = ImageElement.FromBinary(byteArray);
137567 次浏览

使用 BinaryReader 对象从流中返回字节数组,如:

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

在您的问题中,buffer 和 byteArray 似乎都是 byte []。因此:

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

第2行应替换为

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

如果您的文件 InputStream.Position 被设置为流的末尾,那么它将无法工作。 我的补充台词:

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

在 stream. copy to 之前,必须将 stream. position 重置为0; 然后 没问题。

如果使用 Web Pages v2时使用 网页影像类别

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