使用response实现文件的下载

 1、项目结构

使用response实现文件的下载

 代码:

package com.guangtao.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1、获取要下载的文件
        String realPath = "D:\\Java_File\\javaweb-maven-servlet\\response\\src\\main\\resources\\广涛.png";
        System.out.println("要下载的路径: " + realPath);
        // 2、下载的文件命名是啥?   截取到最后的\   索引加1
        String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
        System.out.println(filename);   // 广涛.png
        // 3、加入支持浏览器下载的请求头
        resp.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 = resp.getOutputStream();
        // 7、将FileOutputStream 流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        // 关闭资源
        in.close();
        out.close();
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
上一篇:Vue表单控件绑定


下一篇:Spring文件上传和下载