springboot linux打包后访问不到resources 下面的模板文件
阅读原文时间:2023年07月08日阅读:3

在本地是可以直接获取模板文件并下载,但是服务器上就不行

本地代码:

@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