文件下载至本地

271 阅读1分钟

1. 业务场景:需要从后端下载文件至本地。

解决方法:

发起请求时:请求头 responseType:"blob/ArrayBuffer" (可以获取到后端响应的数据类型是Blob)

封装一个下载函数(使用a标签下载)

function downLoad(url:string,name:string){
    let a = document.createElement('a')
    document.body.appendChild(a)
    a.style.display = 'none'
    a.href = url
    a.download = name
    a.click()
    a.remove()
}

具体使用

接收到后端返回的blob后可以使用URL.createObjectURL(Blob)返回一个下载链接

 const url =  URL.createObjectURL(Blob)
 downLoad(url,name)