• JavaWeb09-Servlet实现下载文件


    DownloadServlet

    public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // String realPath = this.getServletContext().getRealPath("");获取本地文件路径,前提在此目录下确实存在这个文件
    String realPath = this.getServletContext().getRealPath("\images\img01.jpg");
    // 获取下载的文件名
    String fileName = realPath.substring(realPath.lastIndexOf("\") + 1);
    System.out.println(fileName);
    // 让浏览器能支持我们下载我们需要的东西
    // resp.setHeader("Content-Disposition", "attchment;filename=" + fileName);
    // 当文件名为中文时, 会输出不成功, 将使用以下方法解决
    resp.setHeader("Content-Disposition", "attchment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    // 获取下载文件的输入流
    FileInputStream fileInputStream = new FileInputStream(realPath);
    // 创建缓冲区
    int len = 0;
    byte[] buffer = new byte[1024];
    // 获取outputStream对象
    ServletOutputStream servletOutputStream = resp.getOutputStream();
    while((len = fileInputStream.read(buffer)) > 0){
    servletOutputStream.write(buffer, 0, len);
    }
    servletOutputStream.close();
    fileInputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
    }
    }
  • 相关阅读:
    Linux 系统挂载数据盘
    Apache Rewrite规则笔记
    linux fdisk分区笔记
    阿里云linux配置
    linux 下安装mysql相关笔记
    ShopNC目录结构分析
    今天开始出发做ShopNC
    svn相关笔记
    linux学习笔记-不定时更新
    Oracle EBS Java Applet报错:找不到类
  • 原文地址:https://www.cnblogs.com/Patrick20726/p/13583649.html
Copyright © 2020-2023  润新知