前端文件下载实现之blob数据流

459 阅读1分钟
需求

点击下载按钮, 触发文件下载, 其中文件名由后端提供

实现

接口响应的response中, 我们发现content-disposition里面是有后端返回的文件名字, 那么通过headers['content-disposition']获取到值后, 进行正则处理/\w+;filename=(.*)/ 获取括号里边需要的文件名$1 image.png

综上实现代码如下:

async downloadFun() 
      const res = await Api.downloadApi()
      const { status, data, headers } = res.origin
      if (status === 200) {
        const blob = new Blob([data], { type: headers['content-type'] })
        const elink = document.createElement('a')
        // 设置下载文件名
        const filename = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
        elink.download = decodeURIComponent(filename.split('filename=')[1])
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        document.body.removeChild(elink)
      }
 }

关于content-disposition, MDN解释传送门