zoukankan      html  css  js  c++  java
  • 通过blob(用来存储二进制大文件)包装ajax(或axios)请求到的data数据,实现下载EXCEL(或其他如图片等)文件

    //案例一
    axios:设置返回数据格式为blob或者arraybuffer
    如:
        var instance = axios.create({         ... //一些配置
            responseType: 'blob', //返回数据的格式,可选值为arraybuffer,blob,document,json,text,stream,默认值为json
        })
    请求时的处理:
      getExcel().then(res => {
          //这里res.data是返回的blob对象     
          var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
          var downloadElement = document.createElement('a');
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = 'xxx.xlsx'; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象 
     })
    //案例二
    
    function createDownload(fileName, content){
        var blob = new Blob([content]);
        var link = document.createElement("a");
        link.innerHTML = fileName;
        link.download = fileName;
        link.href = URL.createObjectURL(blob);
        document.getElementsByTagName("body")[0].appendChild(link);
    }
    createDownload("download.txt","download file");
    //案例三
    function downloadExport(data) {   return axios.post(url, data).then((res)=>{     const content = res     const blob = new Blob(["uFEFF" + content.data],{ type: "application/vnd.ms-excel;charset=utf-8"})     const fileName = '卡密.xls'     if ('download' in document.createElement('a')) { // 非IE下载       const elink = document.createElement('a')       elink.download = fileName       elink.style.display = 'none'       elink.href = URL.createObjectURL(blob)       document.body.appendChild(elink)       elink.click()       URL.revokeObjectURL(elink.href) // 释放URL 对象       document.body.removeChild(elink)     } else { // IE10+下载       navigator.msSaveBlob(blob, fileName)     }   }); }

      

      

  • 相关阅读:
    隐私政策
    .net打杂工程师的面试感想和总结
    xamarin调试android部署到模拟器错误记录:Deployment failed Mono.AndroidTools.InstallFailedException: Unexpected install output: Error: Could not access the Package Manager. Is the system running?
    C#位运算实际作用之操作整型某一位
    C#位运算实际运用之合并Int
    C#位运算基本概念与计算过程
    ajax异步请求302分析
    http与https区别
    html + css + jquery实现简单的进度条实例
    一个简单的彩色背景图形验证码
  • 原文地址:https://www.cnblogs.com/xuanbingbingo/p/8621755.html
Copyright © 2011-2022 走看看