HttpHandler实现文件下载

•如果HttpHandler输出的是html/txt/jpeg等类型的信息,那么浏览器会直接显示,如果希望弹出保存对话框,则需要添加Header
 
//汉字需要编码,否则会出现乱码....
//将URL编码,解码不需要工作一般是由Web服务器完成,并不需要程序员参与
•string encodeFileName = HttpUtility.UrlEncode(“生活大爆炸117.avi”);或string encodeFileName = context.Server.UrlpathEncode(“生活大爆炸117.avi”);
//设置Response.AddHeader
Response.AddHeader(“Content-Disposition”, string.Format(attachment;filename=\”{0}\“”, encodeFileName));//attachment:附件的方式
•其中filename后为编码后的文件名。filename段为建议的保存文件名。

 

1、新建“一般处理程序”

 1 <%@ WebHandler Language="C#" Class="Handler" %>
 2 
 3 using System;
 4 using System.Web;
 5 
 6 public class Handler : IHttpHandler {
 7     
 8     public void ProcessRequest (HttpContext context) {
 9         string requestFileName = context.Request.QueryString["fn"];
10         context.Response.AddHeader("content-Disposition","attchment;filename="+requestFileName);
11         string phyPath = context.Server.MapPath(requestFileName);
12         context.Response.WriteFile(phyPath);
13         context.Response.End();
14     }
15  
16     public bool IsReusable {
17         get {
18             return false;
19         }
20     }
21 
22 }

2、新建html文件

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 
 3 <html xmlns="http://www.w3.org/1999/xhtml">
 4 <head>
 5     <title></title>
 6 </head> 
 7 <body>
 8 
 9 <a  href="Handler.ashx?fn=baidu.jpg" >点击下载</a>
10 
11 </body>
12 </html>

打开浏览器时: 下载服务器端的“天空.doc”文件

 1 <%@ WebHandler Language="C#" Class="Handler" %>
 2 
 3 using System;
 4 using System.Web;
 5 
 6 public class Handler : IHttpHandler
 7 {
 8 
 9     public void ProcessRequest(HttpContext context)
10     {
11         context.Response.ContentType = "application/octet-stream";
12 
13         /*
14         string filename = "天 空.doc";
15         
16         context.Response.AddHeader(
17             "Content-Disposition",
18             string.Format("attachment; filename={0}", filename)
19             );
20         */
21 
22         string filename = context.Server.UrlPathEncode("天 空.doc");
23         context.Response.AddHeader(
24             "Content-Disposition",
25             string.Format("attachment; filename={0}", filename)
26             );
27 
28         context.Response.TransmitFile(
29             context.Server.MapPath("~/天 空.doc")
30             );
31         //context.Response.AddHeader("Status-Line","http/1.1 302");
32         //context.Response.AddHeader("Location","http://www.baidu.com");
33         //context.Response.Redirect("http://www.baidu.com");
34     }
35 
36     public bool IsReusable
37     {
38         get
39         {
40             return false;
41         }
42     }
43 
44 }

 

posted @ 2013-04-06 16:22  Big.Eagle  阅读(308)  评论(0)    收藏  举报