允许用户通过Response.WriteFile()从我的网站下载

我试图通过点击我的网站上的链接以编程方式下载文件(这是一个位于我的网络服务器上的.doc文件)。 这是我的代码:

string File = Server.MapPath(@"filename.doc"); string FileName = "filename.doc"; if (System.IO.File.Exists(FileName)) { FileInfo fileInfo = new FileInfo(File); long Length = fileInfo.Length; Response.ContentType = "Application/msword"; Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name); Response.AddHeader("Content-Length", Length.ToString()); Response.WriteFile(fileInfo.FullName); } 

这是一个buttonclick事件处理程序。 好的我可以对文件路径/文件名代码做一些事情来使它更整洁,但是当点击按钮时,页面会刷新。 在localhost上,此代码工作正常,并允许我下载文件确定。 我究竟做错了什么?

谢谢

尝试稍加修改的版本:

 string File = Server.MapPath(@"filename.doc"); string FileName = "filename.doc"; if (System.IO.File.Exists(FileName)) { FileInfo fileInfo = new FileInfo(File); Response.Clear(); Response.ContentType = "Application/msword"; Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name); Response.WriteFile(fileInfo.FullName); Response.End(); } 

您可以拥有一个可以链接到的download.aspx页面,而不是按钮单击事件处理程序。

然后,此页面可以在页面加载事件中包含您的代码。 还要添加Response.Clear(); 在您的Response.ContentType =“Application / msword”之前; line并且还添加Response.End(); 在您的Response.WriteFile(fileInfo.FullName)之后; 线。

哦,你不应该在按钮点击事件处理程序中这样做。 我建议将整个事物移动到HTTP处理程序( .ashx )并使用Response.Redirect或任何其他重定向方法将用户带到该页面。 我对这个问题的回答提供了一个样本 。

如果您仍想在事件处理程序中执行此操作。 确保在写出文件后执行Response.End调用。