// that是传入的vue实例
async exportDocumentByPost(urlParams, exportParams, downloadName, that){
const response = await axios({
url: `导出url/${urlParams}`,
method: 'post',
responseType: 'blob', // 这句话很重要
data: exportParams
})
console.log(response)
if (response.status !== 200) {
console.log('网络或服务器异常!')
return
}
const res = await new Promise((resolve, reject) => {
if (response.headers['content-type'].includes('json')) {
// 此处拿到的data才是blob
const { data } = response
const reader = new FileReader()
reader.onload = () => {
const { result } = reader
const errorInfos = JSON.parse(result)
const { message } = errorInfos
that.$message.error(message || '无法导出,请联系管理员')
reject(message)
}
reader.onerror = err => {
reject(err)
}
reader.readAsText(data)
} else {
resolve(response)
}
})
let blob = new Blob([response.data], { type: response.headers['content-type'] })
const a = window.document.createElement('a')
const downUrl = window.URL.createObjectURL(blob)// 获取 blob 本地文件连接 (blob 为纯二进制对象,不能够直接保存到磁盘上)
a.href = downUrl
a.download = `${downloadName}.xls`
a.click()
window.URL.revokeObjectURL(downUrl)
}
参考链接:https://zhuanlan.zhihu.com/p/408866162
网友评论