excel文件导出到HttpServletResponse响应流
一:前提
- excel文件已经存在,excel文件生成可通过easy-excel来实现
二:解决问题
- 导出文件名中文乱码修复
- 通过HttpServletResponse将文件file数据输出到response中
- 前端直接调用接口触发附件下载
三:实现代码
public void fileToResponse(File file, HttpServletResponse response) {
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[bis.available()];
bis.read(buffer);
bis.close();
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
String fileName = file.getName();
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)));
bos.write(buffer);
bos.flush();
bos.close();
} catch (IOException ex) {
throw new XException(ex.getMessage());
}
}
四:简单解释
- response的contentType指定了为excel文件,其他文件不适用
- 文件名进行导出中文乱码问题解决,注意一个点:postman请求会发现中文是乱码的,但是正常浏览器访问却是正常的,说明postman验证还是有一定区别的。