📜  ionic 将 base64 保存为文件 - TypeScript 代码示例

📅  最后修改于: 2022-03-11 14:48:15.256000             🧑  作者: Mango

代码示例1
let UUID = 'empleado-' + (new Date().getTime()).toString(16);

// imagen = data:image/jpeg;base64,/9j/4........
    let realData = imagen.split(",")[1];
    let blob = this.b64toBlob(realData, 'image/jpeg');

    this.file.checkDir(this.file.externalApplicationStorageDirectory, 'DirectorioFotos')
        .then(_ => {
          this.file.writeFile(this.file.externalApplicationStorageDirectory + 'DirectorioFotos/', UUID + '.jpg', blob).then(response => {
            // ACTION
          }).catch(err => {
            // ACTION
          })
        })
        .catch(err => {
          this.file.createDir(this.file.externalApplicationStorageDirectory, 'DirectorioFotos', false).then(result => {
            this.file.writeFile(this.file.externalApplicationStorageDirectory + 'DirectorioFotos/', UUID + '.jpg', blob).then(response => {
              // ACTION
            }).catch(err => {
              // ACTION
            })
          })
        });
 
 //convert base64 to blob
 b64toBlob(b64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 512;
    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      var slice = byteCharacters.slice(offset, offset + sliceSize);

      var byteNumbers = new Array(slice.length);
      for (var i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      var byteArray = new Uint8Array(byteNumbers);

      byteArrays.push(byteArray);
    }

    var blob = new Blob(byteArrays, {type: contentType});
    return blob;
  }