前端axios下载csv文件乱码
大约 2 分钟
问题
现在有个后端下载csv文件的接口,在浏览器地址栏直接请求这个接口,下载的文件用office的excel打开不乱码(wps也能正常显示),但通过页面点击按钮来下载,保存的文件用office的excel打开就乱码(wps还是能正常显示)。
后端代码大概这样:
/**
*
* @param response
* @param checkResultFileUrl 这个文件要求是gkb编码
* @throws IOException
*/
@Override
public void downloadCheckResult(HttpServletResponse response, String checkResultFileUrl) throws IOException {
response.setCharacterEncoding("GBK");
response.addHeader("Content-Disposition", "attachment; filename=checkResult.csv");
response.addHeader("Content-Type", "text/csv");
ServletOutputStream outputStream = response.getOutputStream();
InputStream is = fileStorageService.getFileInputStream(checkResultFileUrl);
byte[] bytes = IOUtils.readFully(is, is.available());
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}
前端代码大概这样:

解决方法
发起请求的时候不设置 responseType: 'blob',并且在downLoadFile函数中类似下面的修改
let resData ='\ufeff' + row.data;
const blob = new Blob([resData], {
type: 'text/csv,charset=UTF-8'
});
成功!!! 关键点是在返回的data 上加上'\ufeff’

系统推荐
- Notion笔记定时备份
- Spring Cloud Gateway收到的是http请求,但schema却是https
- NGINX
- HTTP1 0 vs HTTP1 1 vs WebSocket
- 测试两台服务器间的网速
- InnoDB存储引擎
- Docker笔记
- 分库分表
- AQS源码解读
- Linux dev shm目录
- WebSocket SpringBoot Demo
- https和http混用解决办法
- 随机毒鸡汤:这辈子最想当的就是那种,有两个臭钱就了不起的人。