【问题标题】:How to create byte array from HttpPostedFile如何从 HttpPostedFile 创建字节数组
【发布时间】:2010-09-26 11:17:47
【问题描述】:

我正在使用具有 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);

【问题讨论】:

  • 我们如何在另一个 .aspx 页面中发布文件?
  • 这行 file.InputStream.Read(buffer, 0, file.ContentLength); 不是用输入流中的字节填充缓冲区吗?为什么我们应该使用@Wolfwyrd 在下面的答案中提到的 BinaryReader.ReadBytes(...)ImageElement.FromBinary(buffer); 不能解决问题吗?

标签: c# arrays


【解决方案1】:

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

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

【讨论】:

  • 如下 jeff 所述,b.ReadBytes(file.InputStream.Length);应该是 byte[] binData = b.ReadBytes(file.ContentLength);因为 .Length 是 long 而 ReadBytes 需要一个 int。
  • 记得关闭 BinaryReader。
  • 像魅力一样工作。感谢您提供这个简单的解决方案(与 jeff、Spongeboy 和 Chris 的 cmets)!
  • 二进制阅读器不必关闭,因为有一个使用会在处理时自动关闭阅读器
  • 知道为什么这不适用于 .docx 文件吗? stackoverflow.com/questions/19232932/…
【解决方案2】:
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);

第 2 行应替换为

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

【讨论】:

    【解决方案3】:

    如果您的文件 InputStream.Position 设置为流的末尾,它将不起作用。 我的附加线路:

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

    【讨论】:

      【解决方案4】:

      在您的问题中,缓冲区和 byteArray 似乎都是 byte[]。所以:

      ImageElement image = ImageElement.FromBinary(buffer);
      

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

          对于图像,如果您使用 Web Pages v2,请使用 WebImage Class

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

          【讨论】:

            猜你喜欢
            • 2011-09-28
            • 2011-12-22
            • 1970-01-01
            • 2014-02-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多