2009-06-21 42 views
0

下载我试图通过单击链接,在我的网站(这是一个.doc文件,坐在我的网站服务器上)编程式下载文件。这是我的代码:允许用户从我的网站通过Response.WriteFile()

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事件处理程序中。好吧,我可以做一些关于文件路径/文件名的代码来使它更整洁,但是当点击按钮时,页面刷新。在本地主机上,这段代码工作正常,并允许我下载文件确定。我究竟做错了什么?

感谢

+0

愚蠢的问题:没有“filename.doc”在同一地点存在于服务器上(相对于应用程序根目录)? – Stobor 2009-06-21 22:52:27

+0

是(在根部)。 – dotnetdev 2009-06-21 23:01:28

回答

0

尝试略加修改:

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(); 
} 
0

哦,你不应该这样做在按钮单击事件处理程序。我建议将整个事件移到HTTP处理程序(.ashx),并使用Response.Redirect或任何其他重定向方法使用户访问该页面。 My answer to this question provides a sample

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

1

而不是有一个按钮点击事件处理程序,你可以有一个download.aspx页面,你可以链接到相反。

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

相关问题