zoukankan      html  css  js  c++  java
  • 处理后台返回的文件流,base64码实现文件导出功能

    借鉴文章:https://blog.csdn.net/developer_qi/article/details/87803950 

    一、 处理文件流

        ①  请求接口时,声明responseType: 'blob', 告诉后台需要返回的的报文是文件

    export function writeWithHead(params) {
      return request({
        url: window.CONFIG.restIp + '/workOrderExcelOutDto/writeWithHead',
        method: 'post',
        data: params,
        responseType: 'blob',   // 请求的时候必须添加
        timeout: 200000
      })
    }

      ②  处理后台返回的流数据

    writeWithHead(params).then(res => {
            if (res.status === 200) {
              this.$message({
                type: "success",
                message: '导出成功'
              })
              const blob = new Blob([res.data]);
              const fileName = '导出文件.xlsx';//下载文件名称
              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 {
              this.$message({
                type: "error",
                message: '导出失败'
              });
            }
          });

     二、 base64码  (原理一样,多一步操作,需要将base64码转换成文件流后在操纵)

    writeWithHead(params).then(res => {
       if (res.status === 200) {
         this.$message({
            type: "success",
            message: '导出成功'
           })
         this.downloadFileByBase64(res.data,'导出列表')
     } else { 
       this.$message({ type: "error", message: '导出失败' });
     }});
    dataURLtoBlob (dataurl, filename) {
          let arr = dataurl.split(",");
          let mime = arr[0].match(/:(.*?);/)[1];
          let bstr = atob(arr[1]);
          let n = bstr.length;
          let u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          return new Blob([u8arr], { type: mime });
        },
      downloadFile (url, name = "导出列表") {
          var a = document.createElement("a");
          a.setAttribute("href", url);
          a.setAttribute("download", name);
          a.setAttribute("target", "_blank");
          let clickEvent = document.createEvent("MouseEvents");
          clickEvent.initEvent("click", true, true);
          a.dispatchEvent(clickEvent);
        },
     downloadFileByBase64 (base64, name) {
          let myBlob = this.dataURLtoBlob(base64);
          let myUrl = URL.createObjectURL(myBlob);
          this.downloadFile(myUrl, name);
      },

     有不足之处,还望大佬多指教

  • 相关阅读:
    python第九十天----jquery
    收藏所用C#技术类面试、笔试题汇总
    线程内打开窗体
    有关正则表达式的一些总结
    XML与Object的范型转换
    开始工作了
    Oracle查询数据表结构(字段,类型,大小,备注)
    MyEclipse安装jbpm插件
    MyEclipse启动tomcat增加内存配置
    extJs常用的四种Ajax异步提交
  • 原文地址:https://www.cnblogs.com/cjechenjinge-0820/p/13071652.html
Copyright © 2011-2022 走看看