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標籤下載請求,如文章開篇
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章