文件流互相转换(blob转base64,二进制流)

二进制流格式

在这里插入图片描述

blob格式

跟用input上传文件的获取到的差不多

在这里插入图片描述
用URL.createObjectURL(blob)转化后是这样
在这里插入图片描述

base64格式

在这里插入图片描述

二进制流转blob

getFiles(res, type, filename) {
      // 创建blob对象,解析流数据
      const blob = new Blob([res], {
        // 如何后端没返回下载文件类型,则需要手动设置:type: 'application/pdf;chartset=UTF-8' 表示下载文档为pdf,如果是word则设置为		  msword,excel为excel
        type: type
      });
      const a = document.createElement("a");
      // 兼容webkix浏览器,处理webkit浏览器中href自动添加blob前缀,默认在浏览器打开而不是下载
      const URL = window.URL || window.webkitURL;
      // 根据解析后的blob对象创建URL 对象
      const herf = URL.createObjectURL(blob);
      this.pdfUrl = herf;
    },
this.getFiles((res, "application/pdf;chartset=UTF-8");

blob转base64

    blobToBase64(blob, callback) {
      const fileReader = new FileReader();
      fileReader.onload = (e) => {
        callback(e.target.result);
      };
      fileReader.readAsDataURL(blob);
    },
      this.blobToBase64(blob, (dataurl) => {
        this.pdfBase64 = dataurl;
        console.log("base64", this.pdfBase64);
      });

base64转blob

    base64ToBlob(code) {
      //Base64一行不能超过76字符,超过则添加回车换行符。因此需要把base64字段中的换行符,回车符给去掉,有时候因为存在需要把加号空格之类的换回来,取决于base64存取时的规则。
      code = code.replace(/[\n\r]/g, "");
      var raw = window.atob(code);
      let rawLength = raw.length;
      //转换成pdf.js能直接解析的Uint8Array类型
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      console.log(uInt8Array, "uInt8ArrayuInt8Array");
      console.log(new Blob([uInt8Array], { type: "application/pdf" }));
      return new Blob([uInt8Array], { type: "application/pdf" }); //转成pdf类型
    },

二进制流转base64

    getBase64(data) {
      const blob = new Blob([data], { type: "image/jpg" }); //类型一定要写!!!
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      })
    },
  • 12
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值