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

首先保证 改文件资源能够通过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();
              }
          }
      }

//实现方法如上

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-16 10:56:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-16 10:56:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-16 10:56:01       87 阅读
  4. Python语言-面向对象

    2024-03-16 10:56:01       96 阅读

热门阅读

  1. mysql笔记:20. 什么是数据库六大范式

    2024-03-16 10:56:01       46 阅读
  2. 如何在Flutter中实现网络请求

    2024-03-16 10:56:01       42 阅读
  3. ARM系统编译依赖无法安装

    2024-03-16 10:56:01       42 阅读
  4. HTML世界之标签Ⅳ

    2024-03-16 10:56:01       39 阅读
  5. 什么是web3.0

    2024-03-16 10:56:01       40 阅读
  6. 洛谷P5707上学迟到

    2024-03-16 10:56:01       40 阅读
  7. 胸闷气短、失眠焦虑、植物神经紊乱治疗!

    2024-03-16 10:56:01       47 阅读
  8. 启发式函数--一起学习吧之人工智能

    2024-03-16 10:56:01       39 阅读