zoukankan      html  css  js  c++  java
  • 使用一般处理程序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             }
  • 相关阅读:
    Java不带.classpath的svn项目下载,转成到eclipse中
    eclipse 实用快捷键(最全)
    加密算法IV的作用
    Hadoop环境常用命令
    Centos网络配置
    apache指定的网络名不再可用
    Toritoisegit记住用户名密码
    用JavaScript修改CSS属性的代码
    div 旋转
    过滤器、监听器、拦截器的区别
  • 原文地址:https://www.cnblogs.com/weihanli/p/4122372.html
Copyright © 2011-2022 走看看