1. 须将axios 配置中的responseType
设置为arraybuffer
,这样就不会让表格出现乱码现象; 2. 若是要动态设置文件名则须要让后台将名字设置到响应头中,不然将是一个乱码的文件名; 3. 而后经过<a></a>
标签的特性来自动点击下载文件; 4. 若是要兼容IE则须要利用navigator.msSaveOrOpenBlob
方法; 5. 兼容Firefox 须将<a></a>
标签添加到body
中,最后再移除<a></a>
标签javascript
例子:html
// axios config config = { responseType: 'arraybuffer' } // 返回数据处理 getUserInfoExport(data).then(({data,headers}) => { let blob = new Blob([data], { type: 'application/vnd.ms-excel' }) // 将服务端返回的文件流(二进制)excel文件转化为blob let fileName = headers.filename if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE window.navigator.msSaveOrOpenBlob(blob, fileName) } else { let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob) let downFile = document.createElement('a') downFile.style.display = 'none' downFile.href = objectUrl downFile.download = fileName // 下载后文件名 document.body.appendChild(downFile) downFile.click() document.body.removeChild(downFile) // 下载完成移除元素 // window.location.href = objectUrl window.URL.revokeObjectURL(objectUrl) // 只要映射存在,Blob就不能进行垃圾回收,所以一旦再也不须要引用,就必须当心撤销URL,释放掉blob对象。 } })
原文出处:https://www.cnblogs.com/gaoguowen/p/11270308.htmljava