0
点赞
收藏
分享

微信扫一扫

关于文件的知识点:Blob,Base64,File

年迈的代码机器 2022-04-13 阅读 61
前端

1、window.atob(),window.btoa()

atob:可以解码通过base64编码的字符串数据(ASCLL 到 base64)。

btoa: 从二进制字符串编码成一个base64的ASCLL字符串(base64 到 ASCLL)

2、new unit8Array()

创建一个8位无符号整数值的类型化数组,内容初始化为0

3、charCodeAt()

获取该字符的unicode编码

var str = "HELLO WORLD";
var n = str.charCodeAt(0); // 72

4、window.URL.createObjectURL(),window.URL.revokeObjectURL()

createObjectURL:创建blob类型,或者file类型的链接

revokeObjectURL: 释放链接地址

5、readAsDataURL()

可参考链接:Html5——File、FileReader、Blob、Fromdata对象_ChosenWu的博客-CSDN博客_file撖寡情

常用的场景:

1、图片上传,下载

// 上传图片
uploadImgs(e: any): void {
    const file = e.target.files[0];
    if (file) {
      this.blobToDataURL(file, (base64Url) => {
        this.imgsList.push({
          uid: String(new Date().getTime()),
          size: file.size,
          name: file.name,
          thumbUrl: base64Url,
          type: file.type,
          file: file
        });
        this.imgsList = [...this.imgsList];
      });
    }
  }

  blobToDataURL(blob: any, cb: any): void {
    const reader = new FileReader();
    reader.onload = function (evt: any): any {
      const base64 = evt.target.result;
      cb(base64);
    };
    reader.readAsDataURL(blob);
  }


 // 加载图片
 loadImgs(pic_list: any): void {
    if (pic_list.length > 0) {
      this.imgsList = [];
      pic_list.map(obj => {
        this.repository.getPic({ fileId: obj }).subscribe((result) => {
            const fileName = result.fileName;
            const fileType = 'data:image/jpeg;base64,';
            const content = fileType + result.content;
            this.imgsList.push({
              uid: String(new Date().getTime()),
              size: 0,
              name: fileName,
              thumbUrl: content,
              type: 'data:image/jpeg',
              file: this.dataURLtoFile(content, fileName)
            });
            this.imgsList = [...this.imgsList];
          }, (error) => {});
      });
    }
  }

  dataURLtoFile(dataurl: any, filename: any): any {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
  }

2、文件下载

  downloadExcel(content: any, fileName: any): void { // 处理后端返回的base64,下载到本地
    const aLink = document.createElement('a');
    const blob = this.base64ToBlob(content); // new Blob([content]);
    const evt = document.createEvent('HTMLEvents');
    evt.initEvent('click', true, true); // initEvent 不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
    aLink.download = fileName;
    aLink.href = URL.createObjectURL(blob);
    aLink.click();
  }

  base64ToBlob(code: any): Blob {
    const raw = atob(code);
    const rawLength = raw.length;
    const uInt8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
  }
举报

相关推荐

0 条评论