简体   繁体   中英

Download a file and keeping the original name

After I downloaded a file using this code:

using (FileStream fileStream = File.OpenRead(filePath))
{
    MemoryStream memStream = new MemoryStream();
    memStream.SetLength(fileStream.Length);
    fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);

    Response.Clear();

    Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + item.filename);

    Response.BinaryWrite(memStream.ToArray());
    Response.TransmitFile(filePath);
    Response.Flush();
    Response.Close();
    Response.End();
}

The code works very well, but once I open the docx file after the download it loses its original name and I get the message "the file is corrupt and cannot be opened". this only happened to me with the doc & docx files, I tried for xlsx, jpg, pdf, and it worked very well.

Does this have a relation with my code or is it something else?

I guess your filename has an extension like dotx or dot .

The "t" stands for "Template". The default action for "template" type documents in Microsoft Office is to create a new document from a copy of the template.

Look at the different look of Word document and Word template:

在此处输入图像描述

So, if you want the user to download a document and not a template, create a document from the template and send the document to the user with a docx extension.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM