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;
}
@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()));
}