1、设置响应方式 responseType: 'blob' ,默认响应的为JSON
2、axios响应成功之后,查看浏览器响应结果为乱码的,响应成功
3、创建 Blob 对象 response.data,为响应的数据
axios.post(postUrl, params, { responseType: 'arraybuffer' }).then(response => {
const fileType = [
'application/vnd.ms-excel;charset=utf-8', // xls
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' // xlsx
]
const blob = new Blob([response.data], { type: fileType })
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob)
const contentDisposition = response.headers['content-disposition'] // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
const result = patt.exec(contentDisposition)
const filename = decodeURI(escape(result[1])) // 处理文件名,解决中文乱码问题
downloadElement.style.display = 'none'
downloadElement.href = href
downloadElement.download = filename // 下载后文件名
document.body.appendChild(downloadElement)
downloadElement.click() // 点击下载
document.body.removeChild(downloadElement) // 下载完成移除元素
window.URL.revokeObjectURL(href) // 释放掉blob对象
})
- download 属性设置文件名时,可以直接设置扩展名。如果没有设置,则浏览器将自动检测正确的文件扩展名并添加到文件 。
- 在每次调用createObjectURL()方法时,都会创建一个新的 URL 对象,即使你已经用相同的对象作为参数创建过。当不再需要这些 URL 对象时,每个对象必须通过调用 URL.revokeObjectURL()方法来释放。浏览器会在文档退出的时候自动释放它们,但是为了获得最佳性能和内存使用状况,你应该在安全的时机主动释放掉它们。
- 如果获取不到 response.headers,因该是 axios 的响应拦截器拦截了,改一下就好了