文件下载

场景,工程被打包成jar包,以jar包方式运行。

遇到问题在本地跑起来,下载没问题;但在线上就挂了。

InputStream in = null;
OutputStream out = null;
try {
   //读取文件
   File file1 = ResourceUtils.getFile("classpath:templates/excel/首页数据导入模板.xlsx");
   in = file1.getInputStream();
   //对中文进行编码
   String fileName = URLEncoder.encode("首页数据导入模板.xlsx", "utf-8");
   //设置文件下载的两个头一个流
   response.setContentType("application/vnd.ms-excel");
   response.setHeader("content-disposition", "attachment;filename=" + fileName);
   out = response.getOutputStream();
   //开始下载
   int len;
   byte[] by = new byte[Constant.LEN_6_1024];
   while ((len = in.read(by)) != -1) {
        out.write(by, 0, len);
        out.flush();
      }
   } catch (final UnsupportedEncodingException e) {
        log.error("{}", e.getMessage());
   } catch (final IOException e) {
        log.error("{}", e.getMessage());
   } finally {
        closeStream(in, out);
   }

排查原因,就是因为读取文件方式有问题。遂改之

        InputStream in = null;
        OutputStream out = null;
        try {
            //读取文件
            in = ClassUtils.class.getClassLoader().getResourceAsStream("templates/excel/首页数据导入模板.xlsx");
            //设置文件下载的两个头一个流
            String fileName = URLEncoder.encode("首页数据导入模板.xlsx", "utf-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            out = response.getOutputStream();
            //开始下载
            int len;
            byte[] by = new byte[Constant.LEN_6_1024];
            while ((len = in.read(by)) != -1) {
                out.write(by, 0, len);
                out.flush();
            }
        } catch (final UnsupportedEncodingException e) {
            log.error("{}", e.getMessage());
        } catch (final IOException e) {
            log.error("{}", e.getMessage());
        } finally {
            closeStream(in, out);
        }

具体原因是因为,线上环境,读取下载文件方式不适合,改成了springBoot提供的文件读取方式,就成功了。

下面贴一下,常见项目中资源读取的三种方式:

  A.inOne = request.getServletContext().getResourceAsStream("/templates/excel/首页数据导入模板.xlsx");
  B.File file1 = ResourceUtils.getFile("classpath:templates/excel/首页数据导入模板.xlsx");     
  C.inOne = ClassUtils.class.getClassLoader().getResourceAsStream("templates/excel/首页数据导入模板.xlsx");

第一种是JavaEE,API提供的,局限性很大;第二种是apache提供的方法,第三种是springBoot提供的方法。每种方式都有起局限性,择而用之。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值