开发者

Uploading docx corrupts file

开发者 https://www.devze.com 2023-02-01 04:38 出处:网络
I am using the code below to upload a file.The files upload without error, but when I open a file with a .docx extension M$ says that the file is corrupted.It is able to repair the file and then open,

I am using the code below to upload a file. The files upload without error, but when I open a file with a .docx extension M$ says that the file is corrupted. It is able to repair the file and then open, however. I'd like to fix this so the document opens correctly.

string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fileName = @"C:\" + Guid.NewGuid().ToString() + strExte开发者_运维知识库nsion;
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
    byte[] bytes = new byte[16 * 1024];

    int bytesRead;
    while ((bytesRead = context.Request.InputStream.Read(bytes, 0, bytes.Length)) > 0)
    {
        fs.Write(bytes, 0, bytesRead);
    }
} 

Thanks.

EDITED:

File saves correctly with this code:

while ((bytesRead = context.Request.Files[0].InputStream.Read(bytes, 0, bytes.Length)) > 0)

Also saves correctly with context.Request.Files[0].SaveAs(...);


It looks like you are reading the HttpRequest.InputStream. The better thing to do is check the HttpRequest.Files collection.

(Or even easier, use a FileUpload server control).

Your code is copying the raw input, which is most likely multi-part, to a file.


This doesn't answer your question exactly, but you could use HttpPostedFile.SaveAs to save the content to the desired path.

string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fileName = @"C:\" + Guid.NewGuid().ToString() + strExtension;
context.Request.Files[0].SaveAs(fileName); // i'll ignore the violation of the law of demeter ;)
0

精彩评论

暂无评论...
验证码 换一张
取 消