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

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

正确的下载文件的方法

 1              //获取对应文件的内容,这里主要取comm.FileURL的文件保存动态路径,也就是20150825/5e7af276b7754363a1e78b496e1d1603文本文档.txt
 2             CommNoticeModel comm = CommNoticeBLL.GetInstance().GetCommNoticeModel(int.Parse(Request.QueryString["ID"]));
 3             //这里主要组成文件的相对路径,这里得到的就是  ~/FileBox/20150825/5e7af276b7754363a1e78b496e1d1603文本文档.txt
 4             string path = CommonUtilModel.GetFileVirtualPath() + comm.FileURL;
 5             try
 6             {
 7                               
 8                 FileInfo fileInfo = new FileInfo(Server.MapPath(path));
 9                 Response.Clear();
10                 Response.ClearContent();
11                 Response.ClearHeaders();
12                 Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
13                 Response.AddHeader("Content-Length", fileInfo.Length.ToString());
14                 Response.AddHeader("Content-Transfer-Encoding", "binary");
15                 // 告诉浏览器传递给用用户的是一个非txt,rar等不出现在IEEM上的一个文件,不需要在浏览器页面打开,需要直接下载
16                 Response.ContentType = "application/octet-stream";
17                 Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
18                 Response.WriteFile(fileInfo.FullName);
19                 Response.Flush();
20                 Response.End();             
21             }
22 
23             catch (Exception ex)
24             {
25                 Response.Clear();
26                 Response.ClearContent();
27                 Response.ClearHeaders();
28                 Response.Write(ex.Message + "<br/>" + path);
29                 Response.End();
30             }

转载请注明出处:http://www.cnblogs.com/abc1069/

posted @ 2015-08-25 10:26  醉马踏千秋  阅读(1095)  评论(0编辑  收藏  举报