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

Had*_*ope 25 asp.net file download

从网页上实现使用asp.net 2.0的下载操作的最佳方法是什么?

在名为[Application Root]/Logs的目录中创建操作的日志文件.我有完整的路径,并希望提供一个按钮,单击该按钮将从IIS服务器下载日志文件到用户本地PC.

Mar*_*tin 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();
Run Code Online (Sandbox Code Playgroud)

Response.TransmitFile是发送大文件的可接受方式,而不是Response.WriteFile.

  • 其中一个关键部分是Response.End() - 如果没有它,你最终会偶尔出现损坏的下载,破坏的数字签名,各种各样的怪异. (7认同)

BiL*_*LaL 11

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();
}
Run Code Online (Sandbox Code Playgroud)


更新:

初始代码

Response.AddHeader("Content-Disposition", "inline;attachment; filename=" + fileInfo.Name);
Run Code Online (Sandbox Code Playgroud)

具有"内联;附件",即内容处置的两个值.

不知道它何时开始,但在Firefox中显示正确的文件名.将显示文件下载框,其中包含网页名称及其扩展名(pagename.aspx).下载后,如果将其重命名为实际名称; 文件打开成功.

根据此页面,它按先到先得的原则运作.将值更改为attachment仅解决问题.

PS:我不确定这是否是最佳做法,但问题已得到解决.

  • -1:正如Martin所说,使用TransmitFile而不是WriteFile.WriteFile基本上是针对大文件而破解的 (2认同)