前提:项目中文件导出按钮的文件下载事件,在Edge浏览器上面下载很缓慢并且后端的接口返回的数据都已经返回完,但是前端的下载及其缓慢。这个时候,我并没有做Edge浏览器的兼容处理。
详见如下代码:

点击查看代码
// 下载blob文件
// @param data blob数据
// @param filename 文件名
export function downloadFile(data, filename) {
  if (!data) {
    return
  }
  const bw = getBrowser() // 获取浏览器信息
  if (!bw['edge'] || !bw['ie']) { // 除了edge和ie浏览器之外的浏览器使用a标签下载
    const link = document.createElement('a')
    const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    // 指定下载文件的格式
    link.setAttribute('download', filename + '.xls')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } else if (bw['ie'] >= 10 || bw['edge'] === 'edge') { //edge和ie浏览器的下载方式
    const _utf = '\uFEFF' // 为了使文件以utf-8的编码模式,同时也是解决中文乱码的问题
    const blob = new Blob([_utf + data], {
      type: 'application/vnd.ms-excel', // 自己需要的数据格式
    })
    navigator.msSaveBlob(blob, filename)
  }
}

function getBrowser() { // 不同浏览器
  const sys = {}
  const ua = navigator.userAgent.toLowerCase()
  if (ua.indexOf('edge') !== -1) {
    sys.edge = 'edge'
  } else if (ua.match(/rv:([\d.]+)\) like gecko/)) {
    sys.ie = ua.match(/rv:([\d.]+)\) like gecko/)[1]
  } else if (ua.match(/msie ([\d.]+)/)) {
    sys.ie = ua.match(/msie ([\d.]+)/)[1]
  } else if (ua.match(/firefox\/([\d.]+)/)) {
    sys.firefox = ua.match(/firefox\/([\d.]+)/)[1]
  } else if (ua.match(/chrome\/([\d.]+)/)) {
    sys.chrome = ua.match(/chrome\/([\d.]+)/)[1]
  } else if (ua.match(/opera.([\d.]+)/)) {
    sys.opera = ua.match(/opera.([\d.]+)/)[1]
  } else if (ua.match(/version\/([\d.]+).*safari/)) {
    sys.safari = ua.match(/version\/([\d.]+).*safari/)[1]
  }
  return sys
}

posted on 2022-09-20 10:58  好久不见-库克  阅读(200)  评论(0)    收藏  举报