BytesIO二进制流文件(内存缓存)转json格式传输到前端加码解码base64转文件下载

  Javascript 如何实现base64转文件下载保存到本地

  BytesIO二进制流文件(内存缓存)转json格式传输到前端

  加码

   #读取二进制序列

    io_file = BytesIO()
    f.save(io_file)
    data = io_file.getvalue()
    base64_data = base64.b64encode(data)
    #字符串化,使用utf-8的方式解析二进制
    base64_str = str(base64_data,'utf-8')

  解码

   base64_data = base64_str.encode(encoding='utf-8')

    data = base64.b64decode(base64_data)

  base64转文件下载(方法1)

  

      //将base64转换为blob
      function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(","),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
      }
      // * desc: 下载方法
      // * @param url  :返回数据的blob对象或链接
      // * @param fileName  :下载后文件名标记
      function downloadFile(url, name = "What's the fuvk") {
        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);
      }
      // * desc: 下载参数入口
      // * @param base64  :返回数据的blob对象或链接
      // * @param fileName  :下载后文件名标记
      function downloadFileByBase64(base64, fileName) {
        var myBlob = dataURLtoBlob(base64);
        var myUrl = URL.createObjectURL(myBlob);
        downloadFile(myUrl, fileName);
      }
    

  js弹出文件保存框_js保存文件到本地_ie js下载文件到本地而不是显示

  注意的点:

  bytesio转base64的适合记得要带上header,即mimetype类型

  因为不同的文件类型base64前面拼接的不同

   //根据文件后缀 获取base64前缀不同

     function getBase64Type(type) {
          switch (type) {
            case 'txt': return 'data:text/plain;base64,';
            case 'doc': return 'data:application/msword;base64,';
            case 'docx': return 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,';
            case 'xls': return 'data:application/vnd.ms-excel;base64,';
            case 'xlsx': return 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,';
            case 'pdf': return 'data:application/pdf;base64,';
            case 'pptx': return 'data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,';
            case 'ppt': return 'data:application/vnd.ms-powerpoint;base64,';
            case 'png': return 'data:image/png;base64,';
            case 'jpg': return 'data:image/jpeg;base64,';
            case 'gif': return 'data:image/gif;base64,';
            case 'svg': return 'data:image/svg+xml;base64,';
            case 'ico': return 'data:image/x-icon;base64,';
            case 'bmp': return 'data:image/bmp;base64,';
          }
       
     //附上获取文件后缀的方法  
     function getType(file) {
         var filename = file;
         var index1 = filename.lastIndexOf(".");
         var index2 = filename.length;
         var type = filename.substring(index1 + 1, index2);
         return type;
       },

  base64转文件下载(方法2)

   // * desc: 下载导出文件

    // * @param blob  :返回数据的blob对象或链接
    // * @param fileName  :下载后文件名标记
    // * @param fileType  :文件类 word(docx) excel(xlsx) ppt等
    downloadExportFile(blob, fileName, fileType) {
      const downloadElement = document.createElement('a')
      let href = blob
      if (typeof blob === 'string') {
        downloadElement.target = '_blank'
      } else {
        href = window.URL.createObjectURL(blob) // 创建下载的链接
      }
      downloadElement.href = href
      downloadElement.download = fileName + '.' + fileType // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 触发点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      if (typeof blob !== 'string') {
        window.URL.revokeObjectURL(href) // 释放掉blob对象
      }
    },
    // * desc: base64转文件并下载
    // * @param base64 {String} : base64数据
    // * @param fileType {String} : 要导出的文件类型png,pdf,doc,mp3等
    // * @param fileName {String} : 文件名
    downloadFile(base64, fileName, fileType) {
      const typeHeader = 'data:application/' + fileType + ';base64,' // 定义base64 头部文件类型
      const converedBase64 = typeHeader + base64 // 拼接最终的base64
      const blob = this.base64ToBlob(converedBase64, fileType) // 转成blob对象
      this.downloadExportFile(blob, fileName, fileType) // 下载文件
    }

  使用

   this.downloadFile('你的base64数据','你的文件名称','你的文件数据类型');

  上述方法有一定的问题js保存文件到本地,base64ToBlob方法是缺失的,可以参考方法1中的如何实现,主要干的事就是把base64的数据加上headerjs保存文件到本地,方法1的是在后端实现了,而该方法是在前端js中添加的,只不过方法并没有写,其实就是拼接。

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1366
0 评论
494

发表评论

!