【问题描述】
使用EasyExcel下载文件时,前端获取不到后端返回的文件名,无法下载到本地
【原因分析】
实际上文件的流后端已经返回了,只是缺少了Content-Disposition属性返回,前端无法获取到文件名;
private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
return response.getOutputStream();
}
【解决方案】
需要增加下面这行,后端才能够返回文件名称给前端,前端才可以下载:
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setCharacterEncoding("utf-8");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
return response.getOutputStream();
}