浏览器 实现文件下载 完成回调 兼容ie11

1,307 阅读1分钟

首先保证 改文件资源能够通过get请求或者 post请求拿到,基于此基础上我们可以实现得知下载完成后的回调 代码如下

const getFileAndCallback = (url, callback) => {
	//定义执行作用域
	const that = this;
	//首先 初始化一个原生ajax对象
	const xhr = new XMLHttpRequest();
	//建立xhr请求
	xhr.open("GET", url, true);
	//定义xhr传输格式未blob
	xhr.responseType = "blob";
	//xhr回调函数
	xhr.onload = function(){
		//接口成功响应
		if (this.status === 200){
                  const blob = this.response;
                  //定义fileReader对象
                  const fileReader = new FileReader();
                  //使用fileReader原生api 读取xhr 存入fileReader对象
                  fileReader.readAsDataUrl(blob);
                  //监听fileReader的加载回调
                  fileReader.onload = async function(e){
                      //兼容ie11的写法
                      //ie 11对文件数据的存储转换api是window.navigator.msSaveBlob(this.response, "文件名/fileName") 或者  window.navigator.msSaveOrOpenBlob(this.response, "文件名/ fileName");
                      if (window.navigator.msSaveOrOpenBlob){
                          try {
                              window.navigator.msSaveOrOpenBlob(this.response, ""文件名/fileName"")
                          }catch(e){
                              //日志记录解析失败的情况 理论上不会出现
                          }
                      }else{
                          //ie11意外的文件下载用的是a标签download
                          let a = document.createElement('a');
                          a.download = "文件名/fileName";
                          a.href = e.target.result;
                          a.click();
                      }
                  };
                  //此时已经下载完成 执行回调
                   callback();
              }
          }
      }

//实现方法如上