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

时间:2020-03-05 18:45:53  来源:igfitidea点击:

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

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

解决方案

回答

这是否有帮助:

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。

回答

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:我不确定这是否是最佳做法,但问题已解决。