- decodeURI 解析 后端返回的 res.headers['content-disposition'] 里面名字(URL编码的)
- res.headers['content-disposition'] 这个在 fixfox浏览器 会有一个 *号 比如 filename*=,所以用 split('='),而不用 split('filename='),并跟后端约定好先filename信息放在 res.headers['content-disposition'] 最后一个 = 号,然后前端也是取最后一个。
- 传参的时候记得要带上{responseType: 'blob'}
exportExcelStream('post', TestService.testApi(this.bodyParams)) // 调用
/**
* 文件流方式下载
* @param typeReq {String} 请求方式
* @param paramsReq {Array} 解构后axios需要的参数列表
*/
function exportExcelStream (typeReq, paramsReq) {
Ajax.$http[typeReq](...paramsReq, {responseType: 'blob'}).then((res) => {
const content = res
const blob = new Blob([content.data], {type: 'application/vnd.ms-excel;charset=utf-8'})
const fileNameSplit = res.headers['content-disposition'].split('=')
const fileName = decodeURI(fileNameSplit[fileNameSplit.length - 1]) // 跟后端约定好最后一个值为fileName字段
if ('download' in document.createElement('a')) { // 非IE下载
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放 URL对象
document.body.removeChild(elink)
} else { // IE10+下载
navigator.msSaveBlob(blob, fileName)
}
// if (window.navigator && window.navigator.msSaveOrOpenBlob) { // 也可这么判断IE10+
// window.navigator.msSaveOrOpenBlob(new Blob([data]), fileName)
// }
}).catch((err) => {
})
}