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             }
  • 相关阅读:
    hasCode in Java
    如何区分同一Class的不同实例对象
    如何构建XML文件
    Spring <context:property-placeholder/>的作用
    关于List的几个方法
    Java 中那些不常用的关键字
    设计模式
    Java源代码阅读-Object.toString()
    修复启动项
    centos关闭防火前
  • 原文地址:https://www.cnblogs.com/weihanli/p/4122372.html
Copyright © 2011-2022 走看看