您现在的位置是:首页 > 前端会客厅 > 前端框架前端框架

vue接收后台传的流导出excel

YU到边2021-10-12【前端框架】人已围观

简介解决下载后文件损坏报错问题


download().then(res => {
  if (typeof window.chrome !== 'undefined') {    // 浏览器兼容
  // Chrome version
  const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
  const urls = window.URL.createObjectURL(blob)
  const a = document.createElement('a') // 生成虚拟a标签
  a.href = urls
  a.download = '文件名' + '.xlsx'
  a.click()
  document.body.removeChild(a) // 下载完成移除元素
  window.URL.revokeObjectURL(urls) // 释放掉blob对象
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {
  // IE version
  const blob = new Blob([res], { type: 'application/force-download' })
  window.navigator.msSaveBlob(blob, this.downFileName)
} else {
    // Firefox version
    const file = new File([res], this.downFileName, {type: 'application/force-download'})
    window.open(URL.createObjectURL(file))
  }
  }).catch(err => {
    console.log('err: ', err)
  })

export function download() {
    return fetch({
        url: '/api/noauth/device/download',
        method: 'get',
        responseType: 'blob'
    })
}

需要加responseType: 'blob',否则文件会损坏

注意,excel流文件一定要在请求的时候加上响应类型字段,也就是:responseType: 'blob'或者,responseType: 'arraybuffer' ,否则下载出来的excel文件就会损坏,就会打不开。损坏文件

Tags:

很赞哦! ()

文章评论