如何在asp.net中实现文件下载

25

如何在asp.net 2.0的网页上实现最佳的下载操作?

一个操作的日志文件会被创建在目录 [应用程序根目录]/Logs 中。我已经有完整的路径并想提供一个按钮,当用户点击时将从IIS服务器下载日志文件到本地PC。


你会对小文件使用 Response.TransmitFile() 吗? - Brian G
2个回答

38

这个能帮到你:

http://www.west-wind.com/weblog/posts/76293.aspx

Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt");
Response.TransmitFile( Server.MapPath("~/logfile.txt") );
Response.End();

使用Response.TransmitFile是发送大文件的常用方法,而不是Response.WriteFile。


9
这其中一个关键的部分是Response.End() - 如果没有它,你可能会得到偶尔出现的损坏下载、破碎的数字签名以及各种奇怪的问题。 - Jason Short
这个能被使用或修改来从另一个URL抓取远程文件吗? - AlexVPerl

12

http://forums.asp.net/p/1481083/3457332.aspx

string filename = @"Specify the file path in the server over here....";
FileInfo fileInfo = new FileInfo(filename);

if (fileInfo.Exists)
{
   Response.Clear();
   Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
   Response.AddHeader("Content-Length", fileInfo.Length.ToString());
   Response.ContentType = "application/octet-stream";
   Response.Flush();
   Response.TransmitFile(fileInfo.FullName);
   Response.End();
}


更新:

初始代码

Response.AddHeader("Content-Disposition", "inline;attachment; filename=" + fileInfo.Name);

Content Disposition属性有"inline;attachment",即两个值。

不知道从什么时候开始,在Firefox中 只有 正确的文件名未显示。文件下载框出现网页名称和其扩展名 (pagename.aspx)。下载后,如果将其重命名为实际名称,则可以成功打开文件。

根据此页面,它基于先到先得的原则。将值更改为attachment就解决了这个问题。

PS:我不确定是否这是最佳实践,但问题已解决。


3
如Martin所说,使用TransmitFile而不是WriteFile。对于大文件来说,WriteFile本质上是有问题的。 - Niki
我正在使用 ModalPopupExtender 中的按钮来操作一个更新面板,但它不起作用。然而,如果将按钮移动到 modalpopup/updatepanel 区域之外,则可以完美地工作。有什么好的解决方法吗? - JoeManiaci

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接