……

vue 导出方法blob文件流

Posted on 2023-03-27 19:58  WALL*E  阅读(248)  评论(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)
  }
}