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

posted @ 2020-09-03 14:55  C丶c  阅读(2218)  评论(0编辑  收藏  举报