首页 > 解决方案 > 从浏览器选项卡下载的 Word 文件文件名不正确

问题描述

我试图.docx在浏览器上打开一个文件,但它被下载了。这很好,但下载的.docx文件名不正确。

我正在使用 Chrome 浏览器和 ASP.NET C# 代码。

假设该文件位于网络路径//test/test.docx和 aspx 文件名DownloadTest.aspx中,其中包含下载 word doc 代码。当它被下载时,文件名是DownloadTest.docx而不是test.docx.

下面是代码。

if (!this.IsPostBack)
{
    string filePath = Request.QueryString["FN"];
    Page.Title = filePath;

    this.Response.ClearContent();
    this.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    this.Response.AppendHeader("Content-Disposition;", "attachment;filename=" + Request.QueryString["FN"]);

    this.Response.WriteFile(filePath);
    this.Response.End();
}

标签: asp.net

解决方案


将查询字符串参数的值更改为FN网络文件名 (test.docx)。标Content-Disposition头确定下载时浏览器中的文件名。

换句话说,该标题需要

Content-Disposition: attachment;filename=test.docx

所以你的代码应该是

this.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fn);

其中 fn 等于 test.docx,它可能不是请求参数。在对它们进行任何操作之前,始终检查请求参数值并验证它们是一个好主意。

另请注意,当您添加标题时,不要在其名称后放置分号。


推荐阅读