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

664 阅读1分钟

问题描述: 本地下载模版没问题。服务器下载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());
}

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