jsWEB前端笔记本

前端如何下载文件流

2022-08-22  本文已影响0人  变量只提升声明不提升赋值

大致就是后端返回文件流,前端通过blob对象读取并转成临时地址然后通过a标签下载

data就是后端返回的文件流
type指定MIME类型既媒体类型,指定了媒体类型后就会下载什么类型的文件下来,所以这里一定不要乱指定
 const blob = new Blob([data], {
        type:
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
      })
      const url = window.URL.createObjectURL(blob)
      const aLink = document.createElement('a')
      aLink.style.display = 'none'
      aLink.href = url
      aLink.setAttribute('download', '申请贷款资料.zip')
      document.body.appendChild(aLink)
      aLink.click()
      /** 下载完成移除元素 */
      document.body.removeChild(aLink)
      /** 释放掉blob对象 */
      window.URL.revokeObjectURL(url)

附上常见MIME类型https://blog.csdn.net/john1337/article/details/117279007
在请求前还需要向axios传递responseType参数,表明需要后台返回什么格式

axios.get(this.downloadContractFilePath + contractNo, {
        // 设置返回数据类型,这里我设置的是"blob";
        responseType: 'blob'
    })

另外,setAttribute方法也会修改文件的类型,如果文件名后面写了文件后缀,那下载下来的就会变成后缀的文件类型

上一篇下一篇

猜你喜欢

热点阅读