后端写文件返回前端,出现该错误。
解决
设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
代码
后端
public void exportTemplate(HttpServletResponse response) {
ArrayList<ActiveGifts> activeGifts = new ArrayList<>();
String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "模板文件.xlsx";
// 对文件名进行URI编码
try {
// 清空response
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1") + ";filename*=utf-8''" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
//允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
// 用 EasyExcel 写入响应输出流
EasyExcel.write(response.getOutputStream(), ActiveGifts.class).sheet("模板").doWrite(activeGifts);
} catch (IOException e) {
e.printStackTrace();
}
}
前端
activeGiftsApi.activeGiftsDownloadTemp().then((res) => {let blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'}) // 文件类型console.log(res.headers['content-disposition']); // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx") 设置的文件名;//以=分割取数组[1]元素为文件名let filename = '123123'let url = window.URL.createObjectURL(blob); // 创建下载链接let aLink = document.createElement("a"); // 赋值给a标签的href属性aLink.style.display = "none";aLink.href = url;aLink.setAttribute("download", filename);document.body.appendChild(aLink); // 将a标签挂载上去aLink.click(); // a标签click事件document.body.removeChild(aLink); // 移除a标签window.URL.revokeObjectURL(url); // 销毁下载链接 })