在本地是可以直接獲取模板文件並下載,但是服務器上就不行
本地代碼:
@Override
public void downArchRelayTemplate(HttpServletRequest request, HttpServletResponse response) {
// 定義下載文件名稱
String filename = ArchRelayTemplateEnum.FILENAME.getValue();
// 得到要下載的文件
try {
File file = new File(this.getClass().getResource(ArchRelayTemplateEnum.FILE_PATH.getValue()).toURI());
FileUtil.downFile(request,response,filename,file);
} catch (Exception e) {
e.printStackTrace();
log.error("模板文件下載失敗:"+e.getMessage());
}
}
服務器報錯:{"bizError":false,"code":50001,"message":"文件生成失敗:class path resource [tpl/appointDismiss.docx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/opt/code/cas/target/cas-1.0.0-SNAPSHOT.jar!/BOOT-INF/classes!/tpl/appointDismiss.docx","response":null}
意思讀取不到jar包里面的文件,因為springboot是打包jar包,然后是執行運行的jar包,而不是讀取的target下面編譯好的文件,
解決方案:通過流讀取文件內容然后轉換為文件下載
@Override
public void downArchMaterialRecord(HttpServletRequest request,HttpServletResponse response)throws IOException {
InputStream in = null;
ServletOutputStream out = null;
// 定義下載文件名稱
String filename = "批量新建材料轉出.xls";
// 得到要下載的文件
try {
// 兩種獲取流的方式都可以
//InputStream inputStream = this.getClass().getResourceAsStream("/xls/downArchMaterialRecord.xls");
InputStream inputStream = new ClassPathResource("/xls/downArchMaterialRecord.xls").getInputStream();
File originFile = new File("tempFile.xls");
FileCopyUtils.copy(FileCopyUtils.copyToByteArray(inputStream),originFile);
FileUtil.downFile(request,response,filename,originFile);
FileUtil.deleteDir(originFile.getPath());
} catch (Exception e) {
e.printStackTrace();
log.error("模板文件下載失敗:"+e.getMessage());
}
}
參考:https://stackoverflow.com/questions/25869428/classpath-resource-not-found-when-running-as-jar