文件名和mime问题 - ASP.NET下载文件(C#)

时间:2009-10-06 14:53:40

标签: c# asp.net file download transmitfile

我的ASP.NET应用程序中遇到了一个非常奇怪的问题。

当用户点击下载文件的按钮时,Internet Explorer / Chrome / Firefox会显示保存对话框,但该文件的名称是ASPX页面的名称(例如,如果页面命名为Download.aspx,下载对话框显示“文件”Download.zip)。有时,在使用MIME类型时,下载对话框显示“Download.aspx”。似乎您正在尝试下载该页面,但实际上是正确的文件。

ZIP扩展会发生这种情况,这是我的代码(我认为非常标准):


        this.Response.Clear();
        this.Response.ClearHeaders();
        this.Response.ClearContent();
        this.Response.AddHeader("Content–Disposition", "attachment; filename=" + file.Name);
        this.Response.AddHeader("Content-Length", file.Length.ToString());
        this.Response.ContentType = GETCONTENTYPE(System.IO.Path.GetExtension(file.Name));
        this.Response.TransmitFile(file.FullName);
        this.Response.End();

GetContentType函数只返回文件的MIME。我尝试使用 application / x-zip-compressed multipart / x-zip ,当然还有 application / zip 。使用application / zip Internet Explorer 8显示XML错误。

非常感谢任何帮助。

问候,

3 个答案:

答案 0 :(得分:2)

我正在研究我为处理类似机制所做的工作,这是我正在做的步骤(大胆的项目看似唯一真正的区别):

Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // Excel 2007 format
// ... doing work...
Response.AddHeader("Content-Length", outputFileInfo.Length.ToString());
Response.TransmitFile(outputFileInfo.ToString());
HttpContext.Current.Response.End(); // <--This seems to be the only major difference

虽然this.Response和HttpContext.Current.Response应该是相同的,但可能不是出于某种原因。

答案 1 :(得分:1)

我认为像Response.Redirect(ResolveUrl(file.FullName))而不是Response.TransmitFile(file.FullName)之类的东西就是你想要的。听起来你实际上希望他们的浏览器指向该文件,而不仅仅是将文件作为对当前请求的响应进行传输。

修改:另请参阅此问题How to retrieve and download server files (File.Exists and URL)

更新:根据您的反馈,我认为this正是您所寻找的。

答案 2 :(得分:0)

用于Excel导出

   Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName));

它适用于IE和Firefox。