思路:
-
修改axios请求的responseType为blob
-
创建a标签,设置download属性,插入到文档中并click
方法一:
axios.post(downloadUrl, reqData, {
responseType: 'blob'
}).then(res => {
let blob = res.data
let reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = (e) => {
let a = document.createElement('a')
a.download = fileName
a.href = e.target.result
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
})
方法二:
axios({
method: 'post',
url: 'api/user/',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
},
responseType: 'blob'
}).then(response => {
this.download(response)
}).catch((error) => {
})
methods: {
// 下载文件
download (data) {
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'excel.xlsx')
document.body.appendChild(link)
link.click()
}
}