一、当从接口获取的数据流格式的数据时,进行解析处理,使用blob转换
const blob = new Blob([res.data], {type: 'application/vnd.ms-excel; charset=utf-8'})
解析前的格式:
解析后的数据:
二、创建链接实现浏览器自动下载
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = fileName
link.click()
URL.revokeObjectURL(link.href)
三、请求接口的时候注意类型
{responseType: 'blob'}
三、封装方法
function downloadFile (url, fileName, condition) {
const hide = message.loading('下载中..', 0)
let info = JSON.parse(JSON.stringify(condition))
axios.post(url, {...info}, {responseType: 'blob'}).then(res => {
if (res.code === 200) {
hide()
this.$message.error(res.message)
return
}
const blob = new Blob([res.data], {type: 'application/vnd.ms-excel; charset=utf-8'})
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = fileName
link.click()
URL.revokeObjectURL(link.href)
hide()
this.$message.success('导出成功')
}).catch(err => {
hide()
this.$message.error('导出失败')
})
}