zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    ["Visual Studio快捷键" ,"Vs","IDEA快捷键"]
    文件夹
    x
    软考.第一章-信息化和信息系统
    软考.起航篇
    Global.asax.cs 为 /.aspx 执行子请求时出错。 Server.Transfer
    网关我选 Spring Cloud Gateway
    我面向 Google 编程,他面向薪资编程
    JDK 13 都已经发布了,Java 8 依然是最爱
    Spring Cloud 系列之 Spring Cloud Stream
  • 原文地址:https://www.cnblogs.com/abc1069/p/4756739.html
Copyright © 2011-2022 走看看