https://enable-cors.org/index.html
注意事项:
1.当代码里面使用Content-Disposition来确保浏览器弹出下载对话框的时候。 response.addHeader("Content-Disposition","attachment");一定要确保没有做过关于禁止浏览器缓存的操作。
代码如下:
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
不然会发现下载功能在opera和firefox里面好好的没问题,在IE下面就是不行。
Response Header:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization,DNT,User-Agent,Keep-Alive,Content-Type,accept,origin,X-Requested-With
Access-Control-Allow-Methods: GET,OPTIONS,PUT,DELETE
Access-Control-Allow-Origin: https://wkylin.com.cn
Access-Control-Expose-Headers: Content-Disposition
Connection: keep-alive
Content-Disposition: attachment;filename='wkylin.pdf'
Content-Security-Policy: frame-ancestors *
Content-Type: application/octet-stream; charset=utf-8
Date: Sun, 01 Sep 2019 06:34:20 GMT
Server: nginx/1.10.3 (Ubuntu)
Transfer-Encoding: chunked
Vary: Cookie
X-Frame-Options: SAMEORIGIN, allow-from
下载文件,文件名由后端返回....
api.downloadFiles(params).then(res => {
if (res.data.type.indexOf('json') !== -1) {
message.error('未知错误,请稍候再试!');
} else {
const disposition = res.headers['content-disposition'];
if (disposition) {
const fileName = decodeURI(disposition.split('=')[1].replace(/\'/g, ''));
const blob = new Blob([res.data]);
const downloadElement = document.createElement('a');
const href = URL.createObjectURL(blob); // 创建下载的链接
downloadElement.href = href;
downloadElement.download = fileName; // 下载后文件名
document.body.appendChild(downloadElement); // 追加a标签
downloadElement.click(); // 点击下载
document.body.removeChild(downloadElement); // 下载完成移除元素
URL.revokeObjectURL(href); // 释放掉blob对象
} else {
message.error('未知错误,请稍候再试!');
}
}
})