这位怪蜀黍 中午的时光真难熬!还好有你在!

vue 导出方法blob文件流

Posted on   WALL*E  阅读(280)  评论(0编辑  收藏  举报
axios({
       method: 'get',
       url,
       params,
       headers: {
         'Content-Type': 'application/json; application/octet-stream'
       },
       responseType: 'blob',//这里要注意
       timeout: 100000
     }).then((res) => {
       exportFile(res,'文件.xlsx')
     }).catch(err => {
       reject(err.data)
     })
export function exportFile(res,filename) {
  const str = res.type['application/vnd.ms-excel']
  if (str) {
    console.log('strstrstr',str)
    filename = str.match(/filename=(\S*?)(;|$)/)[1]
  }
  filename = filename || '未命名'
  if ('download' in document.createElement('a')) {
    // 支持a标签download的浏览器
    const downloadElement = document.createElement('a')
    // 谷歌新版本的写法
    // const binaryData = []
    // binaryData.push(res.data)
    const href = window.URL.createObjectURL(new Blob([res]))

    // const href = window.URL.createObjectURL(res.data) // 创建下载的链接
    downloadElement.href = href 
    downloadElement.download = decodeURI(filename) // 下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  } else {
    // 其他浏览器
    navigator.msSaveBlob(blob, fileName)
  }
}
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示