原理
- 设置axios的responseType为blob
- 前端使用Blob接收数据,创建a标签进行保存文件
代码实现
axios.post(url, {...someData}, {responseType: 'blob'})
.then((res) => {
const { data, headers } = res
const fileName = headers['content-disposition'].replace(/\w+;(?:filename\*=utf-8'(?:\w+)?'|filename=)(.*)/, '$1')
const blob = new Blob([data], {type: headers['content-type']})
let dom = document.createElement('a')
let url = window.URL.createObjectURL(blob)
dom.href = url
dom.download = decodeURI(fileName)
dom.style.display = 'none'
document.body.appendChild(dom)
dom.click()
dom.parentNode.removeChild(dom)
window.URL.revokeObjectURL(url)
}).catch((err) => {})
JavaScript