Servlet 浏览器响应文件下载功能实现

achong
2022-04-27 / 0 评论 / 39 阅读 / 正在检测是否收录...
  1. 设置被下载文件

    1. 先设置文件的下载地址
    2. 获取文件名
  2. 设置响应

    1. 设置响应头
  3. 设置文件流

    1. 字节流,更好的传输文件。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取内部文件的下载路径
        String realPath = "D:\\study\\JavaWeb\\IDEA code\\test111\\ResponseDownload\\src\\com\\achong\\resources\\哪吒.png";
        //2.获取下载的文件名(截取文件路径)
        String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
        //3.设置浏览器能够支持下载,注意处理文件名带中文
            //先处理文件中文名问题
        fileName = URLEncoder.encode(fileName, "UTF-8");
            //告诉浏览器要下载该文件(设置响应头)
        response.setHeader("Content-Disposition", "attachment; filename="+fileName);
        //4.获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        //5.创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //6.获取OutputStream对象
        ServletOutputStream out = response.getOutputStream();
        //7.将FileOutputStream流写入buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
        while ((len = in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        
        //最后,关闭流
        in.close();
        out.close();
    }
0

评论 (0)

取消
粤ICP备18061175号-3