无法使用C#下载docx文件

时间:2013-08-23 07:15:29

标签: c# download docx

这是我的代码,我正在尝试下载docx文件。但没有成功。 在我可能会滞后的地方,需要一点点暗示。

if (File.Exists(sTempPath + sCreateFileName))
            {
                FileInfo file =new FileInfo(sTempPath + sCreateFileName);
                Response.ClearContent();
                // LINE1: Add the file name and attachment, which will force the open/cancel/save dialog to show, to the header
                Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                // Add the file size into the response header
                Response.AddHeader("Content-Length", file.Length.ToString());
                // Set the ContentType                        
                Response.ContentType = ReturnExtension(file.Extension.ToLower());
                // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
                Response.TransmitFile(sTempPath + sCreateFileName);
                // End the response
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            } 

和返回内容类型给出了docx文件的内容类型:

"application/ms-word"

其中,如果sTempPath + sCreateFileName是文件的整个路径。

更新 我尝试了内容类型:

application/vnd.openxmlformats-officedocument.wordprocessingml.document

这不起作用。

3 个答案:

答案 0 :(得分:9)

DOCX的正确MIME类型不是application/msword,而是application/vnd.openxmlformats-officedocument.wordprocessingml.document

您指定的MIME类型适用于DOC文件。

此外,您可能需要设置Response.Flush()Response.End()而不是CompleteRequest()

答案 1 :(得分:2)

试试此代码

 string FileName = Path.Combine(Server.MapPath("~/physical folder"), attFileName);
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();

     Response.AddHeader("Content-Disposition", string.Format("attachment; filename = \"{0}\"", System.IO.Path.GetFileName(FileName)));
            response.TransmitFile(FileName);
            response.Flush();
            response.End();

答案 2 :(得分:1)

我遇到了同样的问题。对我来说它有效:

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=myfile.docx");
    Response.BinaryWrite(memStream.ToArray());
    Response.Flush();
    Response.Close();
    Response.End();
}