页面上一个下载按钮,然后文件就哗哗的下载到你的本地了,这其中发生了什么?
1.首先点击按钮触发事件,调用接口去后台请求下载的文件,然后后台会以二进制流的方式把文件传到你这里,这里可能需要一点时间,你可以加个loading的动画,比如这样:
2.对于拿到的文件流,前端会将其转化为blob,并加上保存的分类:
const blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;'});
[data]就是你获取到的二进制流,后面的type就是你需要保存的文件格式,我这里需要保存的是excel的文件 所以上面的类型是xlsx的格式类型;这样一个文件格式是xlsx的blob;
3.对于一些现代浏览器,我们直接可以通过window.URL.createObjectURL方法处理blob,在dom里面创建一个a标签,js模拟点击下载,最后在将创建的a标签删除,
const url = window.URL.createObjectURL(blob);
let link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', title); //文件的保存名称
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
这样就完成了在现代浏览器的下载文件,但是对于一些高版本的IE(IE10以上,不包括IE10)就会出问题
比如这样的错误
我们可以通过判断IE浏览器然后以本地保存的方式;
const ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
ieEDGE = navigator.userAgent.match(/Edge/g),
ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
if (ie && ieVer < 10) {
this.message.error('No blobs on IE<10');
return;
}
if (ieVer > -1) {
window.navigator.msSaveBlob(blob, title);
}
完整代码
downloadFile(title, data: Response) {
const blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;'});
const ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
ieEDGE = navigator.userAgent.match(/Edge/g),
ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
console.log('ie:' + ie);
console.log('ieVer:' + ieVer);
if (ie && ieVer < 10) {
this.message.error('No blobs on IE<10');
return;
}
if (ieVer > -1) {
window.navigator.msSaveBlob(blob, title);
} else {
const url = window.URL.createObjectURL(blob);
let link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', title);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}