react中用axios代替a標簽下載文件,監聽下載進度


// 一般的下載我們如果直接請求的話,那么我們得到的東西基本就是亂碼的。遇到這種情況我們會想到用a標簽或者iframe。但是這樣的下載也會有一個無法避免的地方,就是無法監聽是否下載完成。
// 首先我們先把axios封裝起來
import Axios form 'axios';

/*
 * @params {string} url 請求地址
 * @params {object} resOpts 請求配置參數
 */
const download = (url, resOpts = {}) => {
  const { type = 'get', data = '' } = resOpts
  const queryArgs = {
    url,
    method: type,
    data,
    responseType:'blob' // 這個一定要寫,不然下載的東西會亂碼
  }
  // tips: 這里直接返回的是response整體!
  return Axios.request(queryArgs).catch(err => console.log(err))
}
// 這個方法是我借鑒的其他人的 我自己修改了一部分
convertRes2Blob = (response) =>{ // 提取文件名(這個我提取不出來獲取不到) // const fileName = response.headers['content-disposition'].match( // filename=(.*) // )[1] // 將二進制流轉為blob // 關於blob 可以參考:https://developer.mozilla.org/zh-CN/docs/Web/API/Blob const blob = new Blob([response.data], { type: 'application/octet-stream' }) if (typeof window.navigator.msSaveBlob !== 'undefined') { // 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件 window.navigator.msSaveBlob(blob, decodeURI(filename)) } else { // 創建新的URL並指向File對象或者Blob對象的地址 const blobURL = window.URL.createObjectURL(blob) // 創建a標簽,用於跳轉至下載鏈接 const tempLink = document.createElement('a') tempLink.style.display = 'none' tempLink.href = blobURL tempLink.setAttribute('download', decodeURI(filename)) // 兼容:某些瀏覽器不支持HTML5的download屬性 if (typeof tempLink.download === 'undefined') { tempLink.setAttribute('target', '_blank') } // 掛載a標簽 document.body.appendChild(tempLink) tempLink.click() document.body.removeChild(tempLink) // 釋放blob URL地址 window.URL.revokeObjectURL(blobURL) } }

ps:原文鏈接:https://zhuanlan.zhihu.com/p/77672133


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM