• 文件的下载


    文件的下载:

    1). 步骤:

    I. 设置 contentType 响应头: 设置响应的类型是什么 ? 通知浏览器是个下载的文件

    response.setContentType("application/x-msdownload");

    II. 设置 Content-Disposition 响应头: 通知浏览器不再有浏览器来自行处理(或打开)要下载的文件, 而由用户手工完成

    response.setHeader("Content-Disposition", "attachment;filename=abc.txt");

    III. 具体的文件: 可以调用 response.getOutputStream 的方式, 以 IO 流的方式发送给客户端.

    OutputStream out = response.getOutputStream();
    String pptFileName = "C:\Users\Think Pad\Desktop\__正在上课__\11.尚硅谷_JavaWEB_监听器.pptx";

    InputStream in = new FileInputStream(pptFileName);

    byte [] buffer = new byte[1024];
    int len = 0;

    while((len = in.read(buffer)) != -1){
    out.write(buffer, 0, len);
    }

    in.close();

    out不用关闭,是提供给用户的!

     1 import java.io.FileInputStream;
     2 import java.io.IOException;
     3 import java.io.InputStream;
     4 import java.io.OutputStream;
     5 import java.net.URLEncoder;
     6 
     7 import javax.servlet.ServletException;
     8 import javax.servlet.http.HttpServlet;
     9 import javax.servlet.http.HttpServletRequest;
    10 import javax.servlet.http.HttpServletResponse;
    11 
    12 /**
    13  * Servlet implementation class DownloadServlet
    14  */
    15 public class DownloadServlet extends HttpServlet {
    16     private static final long serialVersionUID = 1L;
    17 
    18     /**
    19      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    20      */
    21     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    22         response.setContentType("application/x-msdownload"); 
    23         
    24         String fileName = "文件下载.pptx";
    25         response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    26         
    27         OutputStream out = response.getOutputStream();
    28         String pptFileName = "C:\Users\Think Pad\Desktop\__正在上课__\JavaWEB_监听器.pptx";
    29         
    30         InputStream in = new FileInputStream(pptFileName);
    31         
    32         byte [] buffer = new byte[1024];
    33         int len = 0;
    34         
    35         while((len = in.read(buffer)) != -1){
    36             out.write(buffer, 0, len);
    37         }
    38         
    39         in.close();
    40     }
    41 
    42 }
    纸上学来终觉浅,觉知此事需躬行
  • 相关阅读:
    RabbitMQ 高可用集群搭建
    Ubuntu16.04 安装RabbitMQ
    surging+CentOS7+docker+rancher2.0 菜鸟部署运行笔记
    查看进程使用swap的状态
    查看磁盘信息命令汇总
    复制一批文件,每个文件名包含日期
    小妙招:yum 夯住了怎么办?
    测试并发数
    centos7安装python3
    使用rsync需要注意的一些问题
  • 原文地址:https://www.cnblogs.com/dreamHighMjc/p/7577264.html
Copyright © 2020-2023  润新知