React中下载导出excel方法封装js&下载两种方式备份总结

export const downloadFile = (filename, fileUrl) => {
  const token = getToken();//获取当前登录的token方法
  const xhr = new XMLHttpRequest()
  const url = fileUrl;//请求的api
  xhr.open('get', url, true)
  xhr.setRequestHeader('Authorization', `${token}`) // 给后端发送请求头
  xhr.responseType = 'blob'
  xhr.onload = function(e) {
    if (this.status === 200) {
      const blob = this.response
      const urlObject = window.URL || window.webkitURL || window
      const export_blob = new Blob([blob])
      const a = document.createElement('a') // 利用a标签特性下载
      const url = urlObject.createObjectURL(export_blob)
      a.href = url
      a.download = filename
      a.click()
    }
  }
  xhr.send()
}

这个使用是在Glory-Fast项目的用户的列表下载模块,用户导出整个用户列表的excel,有兴趣可以看一下项目地址,具体使用位置如下图的用户导出button

现阶段做过的项目涉及下载的有两种
  • 存储在阿里云上的

    • 请求后台拿到鉴权和地址
    • window.location = result;直接下载
export const downloadFile = function (fileurl,downloadToken) {
    var url = appServerUrl;
    const headers = {
      'Content-Type': 'text/plain; charset=UTF-8',
      "Token": downloadToken,
      "Host": host,
     "Connection": 'keep-alive',
     "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36',
     "Accept": '*/*',
     "Referer": appHost,
     "Origin": appHost,
     "Sec-Fetch-Mode": 'no-cors'
};
  return OSS.urllib.request(url, {
    method: 'GET',
    headers
  }).then(function (result) {
    var creds = JSON.parse(result.data);
    var client = new OSS({
      region: region,
      accessKeyId: creds.AccessKeyId,
      accessKeySecret: creds.AccessKeySecret,
      stsToken: creds.SecurityToken,
      bucket: bucket
    });

    var result = client.signatureUrl(fileurl, {
        response: {
        'content-disposition': 'attachment; filename="' + getFilenambypunct(fileurl,'_') + '"'
        }
    });
    window.location = result;

    return result;
     
  });
  
};

  • 请求返回的文件数据流

    • 模拟a标签下载请求,如文章开篇
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章