JAVA服务器下载文件内容为空

11 篇文章 0 订阅

问题描述:
本地下载模版没问题。服务器下载word或者Excel模版内容为空。会在文本内容显示下载成功。

来看一下源代码:

res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
res.setContentType("application/octet-stream;charset=utf-8");

这个代码本地没有问题,也不会报错,具体点进去看HttpServletResponse,就会发现没有setContentType。查看具体版本号为4.0.1,所以服务器导致下载数据为空。

解决方案:

第一种:

将res.setContentType直接添加到Header中。

res.addHeader("Content-Disposition", "attachment; filename=" + fileName);
res.addHeader("Content-Type","application/octet-stream;charset=utf-8");

直接用addHeader就可以解决这个问题。
如果说想用其他的set方法,比如:setContentLengthLong()。还是升级一下HttpServletResponse。

第二种情况:

错误信息:

cannot be resolved to absolute file path because it does not reside in the file system

包路径禁止访问,在获取路径的时候被拦截了。
尝试过各种获取路径的写法,不过在new file()的时候就已经拦截了。
所以改成直接通过ClassPathResource的方式直接读取流。
代码展示:

ServletOutputStream out;
res.addHeader("Content-Disposition", "attachment; filename=" + fileName);
res.addHeader("Content-Type","application/octet-stream;charset=utf-8");
ClassPathResource classPathResource = new ClassPathResource("/template/" + fileName);
try {
    InputStream inputStream = classPathResource.getInputStream();
    out = res.getOutputStream();
    int b = 0;
    byte[] buffer = new byte[1024];
    while ((b = inputStream.read(buffer)) != -1) {
        // 4.写到输出流(out)中
        out.write(buffer, 0, b);
    }
    inputStream.close();
    out.flush();
    out.close();
}  catch (IOException e) {
    e.printStackTrace();
    log.error("报错了:"+e.getMessage());
}

目前找到这两种解决方案,如果还有大佬有别的解决方案还请赐教。感谢各位阅读

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值