fetch下载文件
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
保存文件
[code lang="JS"]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);
}))
}[/code]
参考文章
- https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
- https://github.com/matthew-andrews/isomorphic-fetch/issues/67
- https://www.fullstackmemo.com/2018/03/31/fetch-save-file/
- http://www.ruanyifeng.com/blog/2016/04/cors.html