Loading

使用一般处理程序HTTPHandler下载文件

  一般来说我们可以用HTTPHandler来处理一些简单的逻辑,比如验证码、下载文件等。
  以下载word文档为例讲解一下如何在HHTPHandler中下载文件,不限于word文档,如果下载其他文件,需要注意的是要将“
context.Response.ContentType = "application/msword";
”设置为其他相应格式或通用格式“application/octet-stream”,来看代码
 1             //文件名
 2             const string fileName = "申请表.doc";
 3             //获取文件路径
 4             string path = context.Server.MapPath("./App_Data/") + fileName;
 5             //定义输出MIME类型
 6             context.Response.ContentType = "application/msword";
 7             //以文件流方式下载文件
 8             using (FileStream fs = new FileStream(path, FileMode.Open))
 9             {
10                 //建立一个byte[]字节数组,长度为要下载文件的大小
11                 byte[] bytes = new byte[(int)fs.Length];
12                 //将文件流读取到byte[]字节数组中
13                 fs.Read(bytes, 0, bytes.Length);
14                 //通知浏览器下载文件而不是打开
15                 context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
16                 //将byte[]字节数组写向浏览器
17                 context.Response.BinaryWrite(bytes);
18             }

 

posted @ 2014-11-26 08:05  WeihanLi  阅读(749)  评论(0编辑  收藏  举报