zoukankan      html  css  js  c++  java
  • 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);
    }
    }
  • 相关阅读:
    Kali 2020.3安装docker和vulhub
    Web渗透——身份管理测试
    Web渗透——配置管理测试
    网站信息收集
    linux修改MAC的方法
    '文件上传总结'
    美杜莎和九头蛇的对比
    渗透测试常见开放端口及利用
    Google hacking 语法
    web渗透测试基本步骤
  • 原文地址:https://www.cnblogs.com/Patrick20726/p/13583649.html
Copyright © 2011-2022 走看看