C# 如何从 HttpPostedFile 创建字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/359894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create byte array from HttpPostedFile
提问by frosty
I'm using an image component that has a FromBinary method. Wondering how do I convert my input stream into a byte array
我正在使用具有 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);
采纳答案by Wolfwyrd
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);
}
回答by devio
in your question, both buffer and byteArray seem to be byte[]. So:
在您的问题中,buffer 和 byteArray 似乎都是 byte[]。所以:
ImageElement image = ImageElement.FromBinary(buffer);
回答by devio
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);
回答by tinamou
It won't work if your file InputStream.Position is set to the end of the stream. My additional lines:
如果您的文件 InputStream.Position 设置为流的末尾,它将不起作用。我的附加行:
Stream stream = file.InputStream;
stream.Position = 0;
回答by xpfans
before stream.copyto, you must reset stream.position to 0; then it works fine.
在 stream.copyto 之前,您必须将 stream.position 重置为 0;然后它工作正常。
回答by Jodda
For images if your using Web Pages v2 use the WebImage Class
对于图像,如果您使用 Web Pages v2 使用 WebImage 类
var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream);
byte[] imgByteArray = webImage.GetBytes();