linux找不到项目下的模板(No such file or directory),下载方法

关于查找项目下的模板路径,我之前一直用的
getClass().getResource("/template/excel/" + fileName).getPath();
也没出啥问题,就很神奇的突然不好使了。
报错:(No such file or directory)

解决:

Resource resource = new ClassPathResource(filePath1);
resource.getInputStream();

就没有问题了。
需要注意的是,这里不能用resoutce.getFile();
因为打包后Spring试图访问文件系统路径,但无法访问JAR中的路径。 因此必须使用resource.getInputStream()

另记录一个下载的方法,方便以后使用。

public static void download(String path, HttpServletResponse response,String fileName){
     path = "template/excel/" + path;
    InputStream inputStream = null;
    ServletOutputStream servletOutputStream = null;
        try {
            Resource resource = new ClassPathResource(path);
            if (Objects.isNull(resource)) {
                throw new BadRequestException("文件不存在");
            }
//            String fileName = path.split("/")[path.split("/").length - 1];
            fileName = URLEncoder.encode(fileName, "utf-8");
            response.setHeader("content-type", "application/octet-stream;charset=UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            inputStream = resource.getInputStream();
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                // 召唤jvm的垃圾回收器
                System.gc();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值