SpringBoot 读取文件返回流给前端

default

概要

SpringBoot 读取文件返回流给前端


思路

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
     * 将本地文件转换成流,并添加到 response 中
     *
     * @param filePath 文件路径
     * @throws IOException ioexception
     */
    public static void fileStreamToResponse(String filePath, String charset, String contentType, Boolean isDownload) throws IOException {
        File file = new File(filePath);
        String fileName = file.getName();

        // 设置返回内容
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 设置信息给客户端不解析
        String type = new MimetypesFileTypeMap().getContentType(filePath);
        // 设置contenttype,即告诉客户端所发送的数据属于什么类型
        response.setHeader("Content-type", contentType);
        response.setCharacterEncoding(charset);
        if (isDownload) {
            // 设置扩展头,当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        }

        try (OutputStream outputStream = response.getOutputStream()) {
            // 读取filename
            try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath))) {
                byte[] buffer = new byte[1024];
                int length = -1;
                while ((length = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, length);
                }
            }
        }
    }
Gear(夕照)的博客。记录开发、生活,以及一些不足为道的思考……