axios({
method: 'post',
url: this.path,
headers: {
// 项目请求头需要的信息,如用户登录信息验证等
authorization: sessionStorage.getItem('authorization')
},
data: this.params,
// 如果responseType设为blob的话,返回的文件流将会被转成blob对象
responseType: 'blob'
}).then(res => {
// 读取后端返回的错误信息,Blob.text(),text() 方法返回一个 Promise 对象,包含 blob 中的内容,使用 UTF-8 格式编码。
// https://developer.mozilla.org/zh-CN/docs/Web/API/Blob/text
res.text().then(text => {
if (text) {
try {
// 后端错误信息是个对象数据,可以成功解析
const jsonData = JSON.parse(text)
if (!jsonData.success) {
this.$notify.error(jsonData.message || '下载失败')
}
} catch (e) {
// 解析失败,说明是文件流,下载对象
const link = document.createElement('a')
const contentType = this.params.contentType ? this.params.contentType : 'application/vnd.ms-excel'
const blob = new Blob([res], { type: contentType })
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
if (this.params.type && this.params.type === '1') {
link.setAttribute('download', this.params.fileName + `.xlsx`)
} else {
link.setAttribute('download', this.params.fileName + `.xls`)
}
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
})
})