封装一个post请求blob流下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// blob流下载
getDownloadFile(sendMessage, url) {
axios({
url: url,
method: 'post',
data: sendMessage,
responseType: 'blob',
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
const blob = new Blob([res.data], {
type: 'application/vnd.ms-excel'
})
const fileName = decodeURIComponent(res.headers['content-disposition'].split('=')[1])
const linkNode = document.createElement('a')
linkNode.download = fileName // a标签的download属性规定下载文件的名称
linkNode.style.display = 'none'
linkNode.href = URL.createObjectURL(blob) // 生成一个Blob URL
document.body.appendChild(linkNode)
linkNode.click() // 模拟在按钮上的一次鼠标单击
URL.revokeObjectURL(linkNode.href) // 释放URL 对象
document.body.removeChild(linkNode)
})
}