在 中有说关于前后端分离时如何实现文件下载的功能,但是过完年回来,同事告诉我这个方式在ie11上存在不兼容的问题,报如下错:
浏览器兼容问题是很头疼的问题,因为之前也没遇到过这样的问题,所以经过两三个小时才解决。
发现在微软在ie10 和ie11中有两个特有的方法:window.navigator.msSaveBlob
和window.navigator.msSaveOrOpenBlob 方法,这两个方法的区别在于,前者只有保存,后者有保存和打开两个选项,按个人喜好使用就行。
优化之后的代码如下:
1 /** 2 * 导出用户列表 3 */ 4 private exportUsers(){ 5 this.http.doPost({ 6 url: 'system/sysmanager/user/exportUsers', 7 responseType:ResponseContentType.Blob, 8 body:this.form, 9 success: (req, res) => {10 if(window.navigator.msSaveOrOpenBlob){11 // 兼容ie1112 try{13 var blobObject = new Blob([res.json()]); 14 window.navigator.msSaveOrOpenBlob(blobObject, "用户列表.xlsx"); 15 }16 catch(e){17 console.log(e);18 }19 }20 else{21 var blob = new Blob([res.json()]); 22 var a = document.createElement('a');23 a.href = URL.createObjectURL(blob); // xhr.response is a blob24 a.download = "用户列表.xlsx";25 a.style.display = 'none';26 document.body.appendChild(a);27 a.click();28 a.remove();29 }30 }31 });32 }
如果有什么不当之处,请大家多多指出。