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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值