我要读取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文件,它就可以正常工作。
由于
答案 0 :(得分:1)
byte[] myFile;
using (var memoryStream = new MemoryStream())
{
httpPostedFileBase.InputStream.CopyTo(memoryStream);
myFile = memoryStream.ToArray();// or use .GetBuffer() as suggested by Morten Anderson
}
答案 1 :(得分:0)
这是有效的,我自己使用它上传的图像。
public ActionResult Create(Model myModel, HttpPostedFileBase fileUpload)
{
byte[] Data = null;
using (var binaryReader = new BinaryReader(fileUpload.InputStream))
{
Data = binaryReader.ReadBytes(fileUpload.ContentLength);
}
}