Search code examples
angularfile-accessfilesystem-access

Getting Images out of the filesystemAPI (using Angular2+)


I play around with the filesystemAPI. At this moment I can take pictures with ngx.webcam, next I take the Base64, convert it into a blob and then save the blob with filesystemAPI:

const imageName = 'imgName';
const blobImage = this.convert(this.webcamImage.imageAsBase64, imageName);

this.windowRef.nativeWindow.navigator.webkitPersistentStorage.requestQuota(1024 * 1024, (grantedBytes) => {
      this.windowRef.nativeWindow.webkitRequestFileSystem(this.windowRef.nativeWindow.PERSISTENT, 
       grantedBytes, (fs) => {
          ((f) => {
            this.filePath(fs.root, this.path.split('/'), blobImage, f, fs);
          })(blobImage);
      });
});
filePath(rootDirEntry, folders, blobImage, f, fs) {
    // Throw out './' or '/' and move on to prevent something like '/foo/.//bar'.
    if (folders[0] === '.' || folders[0] === '') {
      folders = folders.slice(1);
    }
    rootDirEntry.getDirectory(folders[0], { create: true }, (dirEntry) => {
      // Recursively add the new subfolder (if we still have another to create).
      if (folders.length) {
        this.filePath(dirEntry, folders.slice(1), blobImage, f, fs);
      }
      if (!folders.length) {
        rootDirEntry.getFile(blobImage.name, { create: true, exclusive: true }, (fileEntry) => {
          fileEntry.fullPath = '/' + this.path + blobImage.name;
          fileEntry.createWriter((fileWriter) => {
            fileWriter.write(f); // Note: write() can take a File or Blob object.
          });
        });
      }
    });
}
convert(base64, imageName) {
    const imageBlob = this.dataURItoBlob(base64);
    const imageFile = new File([imageBlob], imageName, { type: 'image/jpeg' });
    return imageFile;
}

  dataURItoBlob(dataURI) {
    const byteString = window.atob(dataURI);
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const int8Array = new Uint8Array(arrayBuffer);
    for (let i = 0; i < byteString.length; i++) {
      int8Array[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([int8Array], { type: 'image/jpeg' });
    return blob;
}

Now if I go through my directory it shows my blob (the name of my blob).

Yet I want to get my blob out of my directory and see the image i´ve token. A .txt file I could show with:

text() {
    this.windowRef.nativeWindow.navigator.webkitPersistentStorage.requestQuota(1024 * 1024, 
      (grantedBytes) => {
        this.windowRef.nativeWindow.webkitRequestFileSystem(this.windowRef.nativeWindow.PERSISTENT, 
         grantedBytes, (fs) => {
           this.onInitFs(fs);
        });
    });
}

onInitFs(fs) {
   fs.root.getFile('testFileSystemAPI.txt', {}, (fileEntry) => {

      // Get a File object representing the file,
      // then use FileReader to read its contents.
      fileEntry.file((file) => {
        const reader = new FileReader();

        reader.onloadend = function(e) {
          const txtArea = document.createElement('textarea');
          txtArea.value = this.result as string;
          document.body.appendChild(txtArea);
        };

        reader.readAsText(file);
      });
});

but if I try to transfer it to my problem it doesn´t work. My last try:

bilderAnzeigen() {
    this.windowRef.nativeWindow.navigator.webkitPersistentStorage.requestQuota(1024 * 1024, 
      (grantedBytes) => {
         this.windowRef.nativeWindow.webkitRequestFileSystem(this.windowRef.nativeWindow.PERSISTENT, 
          grantedBytes, (fs) => {
            this.bA2(fs.root, this.path.split('/'));
      });
    });
}

bA2(rootDirEntry, folders) {
    const dirReader = rootDirEntry.createReader();
    let entries = [];

    if (folders.length - 2 && folders.length - 3) {

      // Call the reader.readEntries() until no more results are returned.
      const readEntries = () => {
        dirReader.readEntries((results) => {
          if (!results.length) {
            this.listResults(entries);
          } else {
            entries = entries.concat(this.toArray(results));
            this.bilderArray = this.bilderArray.concat(this.toArray(results));
            readEntries();
            rootDirEntry.getFile(entries[0].name, {}, (fileEntry) => {
              fileEntry.file((file) => {
                const reader = new FileReader();

                this.imgsrc = reader.result;

                reader.onload = (e) => {
                  this.imgsrc = e.target.result;
                };
              });
            });
          }
        });
      };
      readEntries(); // Start reading dirs.

    }
    // Throw out './' or '/' and move on to prevent something like '/foo/.//bar'.
    if (folders[0] === '.' || folders[0] === '') {
      folders = folders.slice(1);
    }
    rootDirEntry.getDirectory(folders[0], { create: true }, (dirEntry) => {
      // Recursively add the new subfolder (if we still have another to create).
      if (folders.length) {
        this.bA2(dirEntry, folders.slice(1));
      }
    });
  }
toArray(list) {
    return Array.prototype.slice.call(list || [], 0);
  }

  listResults(entries) {
    // Document fragments can improve performance since they're only appended
    // to the DOM once. Only one browser reflow occurs.
    const fragment = document.createDocumentFragment();

    // this.bilderArray.forEach((bild, i) => { console.log(bild.name); });

    entries.forEach((entry, i) => {
      // console.log(entry);
      const img = entry.isDirectory ? '<img src="folder-icon.gif">' :
        '<img src="file-icon.gif">';
      const li = document.createElement('li');
      li.innerHTML = [img, '<span>', entry.name, '</span>'].join('');
      fragment.appendChild(li);

      // this.getbase64(entry, i);


    });

    document.querySelector('#filelist').appendChild(fragment);
  }

My brain got stucked. Does anyone know, how i can get my image out?


Solution

  • I've found a Solution,

    TS:

      showImg() {
        this.windowRef.nativeWindow.navigator.webkitPersistentStorage.requestQuota(1024 * 1024, (grantedBytes) => {
          this.windowRef.nativeWindow.webkitRequestFileSystem(this.windowRef.nativeWindow.PERSISTENT, grantedBytes, (fs) => {
            this.onInitFsShowImg(fs);
          });
        });
      }
    
      onInitFsShowImg(fs) {
    
        fs.root.getFile('myImg.png', {}, (fileEntry) => {
          fileEntry.file((file) => {
            const reader = new FileReader();
    
            reader.readAsDataURL(file);
            reader.onload = (event) => {
              this.imgURL = reader.result;
            };
          });
        });
      }
    

    HTML:

    <img [src]="imgURL">