Spring boot中下载文件的2种方式

1. 通过HttpServletResponse的OutputStream实现

@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
    log.info("进入下载方法。。。。");
    String fileName = "CentOS-7-x86_64-Minimal-1810.iso";// 设置文件名,根据业务需要替换成要下载的文件名
    if (fileName != null) {
        //设置文件路径
        String realPath = "D:\\tmp\\";
        File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/octet-stream");//
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("success");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return null;
}

2. 通过ResponseEntity<InputStreamResource>实现

@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> downloadFile(String fileName)
    throws IOException {
    log.info("进入下载方法...");
    //读取文件
    String filePath = "D:/tmp/" + fileName + ".iso";
    FileSystemResource file = new FileSystemResource(filePath);
    //设置响应头
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");

    return ResponseEntity
        .ok()
        .headers(headers)
        .contentLength(file.contentLength())
        .contentType(MediaType.parseMediaType("application/octet-stream"))
        .body(new InputStreamResource(file.getInputStream()));
}