首先需要设置响应类型为blob
axios({
method: 'GET',
url: '/xxx',
params: xxx,
responseType: 'blob',
})
具体下载代码
let result = await axios({
method: 'GET',
url: '/xxx',
params: xxx,
responseType: 'blob',
})
const a = document.createElement('a')
a.download = '下载图片.jpg'
a.style.display = 'none'
a.href = URL.createObjectURL(result)
document.body.appendChild(a)
a.click()
// 下载完将元素对象移除
URL.revokeObjectURL(a.href)
document.body.removeChild(a)
涉及到的内容
URL.createObjectURL() 静态方法会创建一个 DOMString,其中包含一个表示参数中给出的对象的 URL,这个新的 URL 对象表示指定的 File 对象或 Blob 对象。
URL.revokeObjectURL():
在每次调用 createObjectURL() 方法时,都会创建一个新的 URL 对象,即使你已经用相同的对象作为参数创建过。当不再需要这些 URL 对象时,每个对象必须通过调用 URL.revokeObjectURL() 方法来释放。
更多关于URL对象的信息请参考: https://developer.mozilla.org/zh-CN/docs/Web/API/URL