springboot linux打包后訪問不到resources 下面的模板文件


在本地是可以直接獲取模板文件並下載,但是服務器上就不行

本地代碼:

@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



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM