Springboot 下载文件遇到的坑

最近开发点小功能,有下载excel模板文件的需求,途中遇到了一个坑,特此记录一下,让有同样疑惑的小伙伴不用在浪费时间。

坑:

以下是模板文件在项目中的位置:

模板文件位置

这是相关代码:(问题代码)

   public void templateFileDownload(HttpServletResponse response) throws Exception {

        //获取文件的路径
        String path = getClass().getResource("/template/" + TEMPLATE_FILE_NAME).getPath();
        //解决文件名乱码
        String filePath = URLDecoder.decode(path, "UTF-8");
        // 设置输出的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String encodeFileName = URLEncoder.encode(TEMPLATE_FILE_NAME, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName);
        FileUtils.copyFile(new File(filePath), response.getOutputStream());
        response.flushBuffer();

    }

用post本地测试是可以下载的(这里还有个问题就是postman下载的文件名字一直是<response.xlsx>,我怎么设置都没有用,postman是会有这个问题的,遇到了不用纠结直接跳过。)

放到测试环境之后,springboot项目打成jar包之后这样会提示:No such file or directory

经查jar中的文件要通过流的方式输出,改为以下方式即可:

public void templateFileDownload(HttpServletResponse response) {

        //获取文件的路径 (打包后获取方式)
        try (InputStream inputStream = this.getClass().getResourceAsStream("/template/" + TEMPLATE_FILE_NAME); ServletOutputStream out = response.getOutputStream();) {

            //  设置输出的格式
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String encodeFileName = URLEncoder.encode(TEMPLATE_FILE_NAME, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName);

            int i;
            while ((i = inputStream.read()) != -1) {
                out.write(i);
            }
            out.flush();
        } catch (IOException e) {
            log.info("模板下载失败:{}", e.toString());
        }

    }

另外:你可以试试jdk1.7以后关闭资源的新方式,try with resource 只要这个资源实现了Closeable接口,你就可以很方便的把他放在try()中

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值