从httppostdfilebase读取字节
本文关键字:字节 读取 httppostdfilebase | 更新日期: 2023-09-27 18:04:29
我想读取docx文件的字节,我有这个方法:
public ActionResult Create(Model myModel, HttpPostedFileBase fileUpload)
{
MemoryStream ms = new MemoryStream();
byte[] bin = new byte[100];
long rdlen = 0;
long totlen = fileUpload.InputStream.Length;
int len;
while (rdlen < totlen)
{
len = fileUpload.InputStream.Read(bin, 0, 100);
ms.Write(bin, 0, len);
rdlen += len;
}
}
文件的总长度是11338,但是它只读取到11326,然后它陷入了一个无限循环,因为当它到达11326时,这个len = fileUpload.InputStream.Read(bin, 0, 100);
只返回0作为一个值。奇怪的是,如果我上传一个txt文件,它会正常工作。
谢谢
byte[] myFile;
using (var memoryStream = new MemoryStream())
{
httpPostedFileBase.InputStream.CopyTo(memoryStream);
myFile = memoryStream.ToArray();// or use .GetBuffer() as suggested by Morten Anderson
}
这行得通,我自己用它上传图片。
public ActionResult Create(Model myModel, HttpPostedFileBase fileUpload)
{
byte[] Data = null;
using (var binaryReader = new BinaryReader(fileUpload.InputStream))
{
Data = binaryReader.ReadBytes(fileUpload.ContentLength);
}
}