添加拦截器 在vue框架当中,数据请求是借助axios的,为此,在发送请求的时候,需要修改responseType,改为arraybuffer,blob,axios默认情况下responseType为json,若是不修改,很可能下载时候会是乱码,或者为null。
downloadService.interceptors.response.use(
response => {
// 导出
const headers = response.headers
if(headers['content-type'] === 'application/vnd.ms-excel;charset=UTF-8'){
return response.data
}
},
error => {
return Promise.reject(error)
}
)
export function download(data, name) {
const content = data
const blob = new Blob([content])
const fileName = name
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)
}
}