0

我正在开发一项功能,在从本机相机捕获图像后上传图像。但是将 file_uri 转换为 blob 存在问题。它不会继续 readAsArrayBuffer。将 file_uri 转换为 blob 的任何其他解决方案?

fileUriToBlob(imageData) {
    return new Promise((resolve, reject) => {
      let fileName = "";
      this.file
        .resolveLocalFilesystemUrl(imageData)
        .then(fileEntry => {
          let { name, nativeURL } = fileEntry;

          // get the path..
          let path = nativeURL.substring(0, nativeURL.lastIndexOf("/"));
          console.log("path", path);
          console.log("fileName", name);

          fileName = name;

          // we are provided the name, so now read the file into a buffer
          return this.file.readAsArrayBuffer(path, name);
        })
        .then(buffer => {
          // get the buffer and make a blob to be saved
          let imgBlob = new Blob([buffer], {
            type: "image/jpeg"
          });
          console.log(imgBlob.type, imgBlob.size);

          // pass back blob and the name of the file for saving
          // into fire base
          resolve({
            fileName,
            imgBlob
          });
        })
        .catch(e => reject(e));
    });
  }

来源:https ://github.com/aaronksaunders/ionic4-firebase-storage

编辑:

试过这个

imageToBlob(b64Data: string, contentType: string, sliceSize: number = 512) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    let byteCharacters = atob(b64Data.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''));
    let byteArrays = [];

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

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

      let byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }
    this.blobImage = new Blob(byteArrays, { type: contentType });
    return this.blobImage;
  }

但是我遇到了这个错误:DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correct encoding.

4

1 回答 1

0

你需要确保你已经安装了cordova-plugin-file

请参阅 Ionic 文档 - https://ionicframework.com/docs/native/file

于 2019-09-24T13:09:10.843 回答