前台下载后台返的二进制文件流
# 需求
前端下载文件,发起请求,后端返回二进制流
# 实现
- 考虑到项目中可能涉及多处下载,所以进行axios统一拦截
//axios 拦截器添加判断
/// response 响应拦截 查看请求头是否为blob类型
response => {
if(response.config && response.config.responseType == 'blob') {
//type内写请求头的类型
const blob = new Blob([response.data], { type: 'application/octet-stream;charset=utf-8' }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
let filename = decodeURI(response.headers['filename']);
if ('download' in document.createElement('a')) {
const downloadElement = document.createElement('a');
let href = '';
if(window.URL) href = window.URL.createObjectURL(blob);
else href = window.webkitURL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = filename;
document.body.appendChild(downloadElement);
downloadElement.click();
if(window.URL) window.URL.revokeObjectURL(href);
else window.webkitURL.revokeObjectURL(href);
document.body.removeChild(downloadElement);
} else {
navigator.msSaveBlob(blob, filename);
}
return;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
编辑 (opens new window)
上次更新: 2024/03/06, 09:47:28