項目會碰到很多問題代虾,記錄一下
- 下載本地資源文件激蹲,本地可以下載学辱,jar包下載不了,如何解決衙傀?原因是什么着降?
- 問題描述
controller下載項目相對路徑文件,用 ResourceUtils.getURL("classpath:").getPath() + "static/" + fileName; 獲取資源蓄喇,本地啟動能獲取妆偏,jar包形式啟動獲取不到盅弛, - 修復(fù)方案
改成 “ this.getClass().getClassLoader().getResourceAsStream("static/" + fileName) ” 方式可以
具體下載代碼
# 修改前
@PostMapping("/download")
public ResponseEntity<InputStreamResource> donwload(HttpServletResponse response, String fileName) {
try {
String courseFile = ResourceUtils.getURL("classpath:").getPath() + "static/" + fileName;
# jar包打印出來的路徑為 : file:/xxx.jar!/BOOT-INF/classes!/static/文件名xlsx
logger.info("common download tmp courseFile={}", courseFile);
FileSystemResource file = new FileSystemResource(courseFile);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
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()));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
# 修改后
@PostMapping("/download")
public ResponseEntity<InputStreamResource> donwload(HttpServletResponse response, String fileName) {
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(this.getClass().getClassLoader().getResourceAsStream("static/" + fileName)));
}
- 原因分析