fetch跨域下载文件
为何读取到的content-disposition
header为null
在跨域访问时,XMLHttpRequest对象的getResponseHeader()方法只能拿到一些最基本的响应头,
- Cache-Control
- Content-Language
- Content-Type
- Expires
- Last-Modified
- Pragma
如果要访问其他头,则需要服务器设置Access-Control-Expose-Headers
Access-Control-Expose-Headers:Content-Disposition
保存文件
fetch(`${url}`, {
method: 'POST',
headers: {
...
},
mode: 'cors',
body: JSON.stringify({
companyId: this.state.params.companyId,
startDate: this.state.listParams.startDate,
endDate: this.state.listParams.endDate,
})
}).then(res => res.blob().then(blob => {
let a = document.createElement('a');
let url = window.URL.createObjectURL(blob); // 获取 blob 本地文件连接 (blob 为纯二进制对象,不能够直接保存到磁盘上)
let disposition = res.headers.get('content-disposition');
let filename = (disposition && disposition.replace(/attachment;.*filename=/, '')) || 'uv.xls'
console.log('disposition:', disposition)
console.log('filename:', filename)
a.href = url;
a.download = filename;
a.click();
// 使用完ObjectURL后需要及时释放, 否则会浪费浏览器存储区资源.
window.URL.revokeObjectURL(url);
}))
}
参考文章