一些网页的数据处理函数包括blob对象和bloburl和dataURL互转

一些网页的数据处理函数包括blob对象和bloburl和dataURL互转
包括一些参考资料

const data = {
  // dataurl数据转blob文件
  // 什么是DataUrl?https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  // 什么是blob? https://developer.mozilla.org/zh-CN/docs/Web/API/Blob
  // 此函数网上极为常见,eslint之后略有变化。
  dataURLtoBlob(dataurl) {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    // eslint-disable-next-line no-plusplus
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  },
  // 在h5环境下,bloburl转blob对象
  h5BlobUrlToBlobObj(url) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = function onload(e) {
        if (this.status === 200) {
          const Blob = this.response;
          resolve(Blob);
        } else {
          reject(this.status, e);
        }
      };
      xhr.send();
    });
  },
  // blob对象转blobUrl
  // 参考 https://www.jianshu.com/p/75bfd7cd9e1b
  blobObjToBlobUrl(obj) {
    return (URL || webkitURL).createObjectURL(obj);
  },
  /// /拷贝数据scheme中指明的数据,没有不拷贝
  // 用于从一份完整数据中,抽离部分数据(某个模块)使用
  copyDataByScheme(source, scheme) {
    const retData = {};
    if (source && scheme) {
      // eslint-disable-next-line no-restricted-syntax
      for (const key in scheme) {
        if (scheme[key] !== undefined) {
          retData[key] = source[key];
        }
      }
    }
    return retData;
  },
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值