您的位置:首页 > 编程语言 > ASP

asp.net 文件下载(txt,rar,pdf,word,excel,ppt)

2015-08-25 10:26 756 查看
aspx 文件下载说起来一点都不难,但是在做的过程中还是遇到了一些小小的问题,就是因为这些小小的问题,导致解决起来实在是太难了,其中一个就是Response.End();导致下载文件出现线程终止的情况...

正确的下载文件的方法

//获取对应文件的内容,这里主要取comm.FileURL的文件保存动态路径,也就是20150825/5e7af276b7754363a1e78b496e1d1603文本文档.txt
CommNoticeModel comm = CommNoticeBLL.GetInstance().GetCommNoticeModel(int.Parse(Request.QueryString["ID"]));
//这里主要组成文件的相对路径,这里得到的就是  ~/FileBox/20150825/5e7af276b7754363a1e78b496e1d1603文本文档.txt
string path = CommonUtilModel.GetFileVirtualPath() + comm.FileURL;
try
{

FileInfo fileInfo = new FileInfo(Server.MapPath(path));
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
// 告诉浏览器传递给用用户的是一个非txt,rar等不出现在IEEM上的一个文件,不需要在浏览器页面打开,需要直接下载
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}

catch (Exception ex)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Write(ex.Message + "<br/>" + path);
Response.End();
}


转载请注明出处:http://www.cnblogs.com/abc1069/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: