当前位置:  开发笔记 > 后端 > 正文

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

如何解决《如何在asp.net中实现文件下载》经验,为你挑选了2个好方法。

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

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



1> Martin..:

这有用吗:

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.


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

2> BiLaL..:

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);

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

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

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

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


-1:正如Martin所说,使用TransmitFile而不是WriteFile.WriteFile基本上是针对大文件而破解的
推荐阅读
ERIK又
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有