Home > Net >  AngularFire Storage - How to await for two images to upload before updating a document
AngularFire Storage - How to await for two images to upload before updating a document

Time:11-04

I have two images I want to upload. The image is the same, but I have resized them differently. As a result, there are two upload tasks that are in process. Currently, I'm waiting for the large image to upload before updating a firestore document. However, a more ideal approach would be to wait for both to complete before updating a document.

As outlined below, I'm only monitoring the largeTask. Ideally, I would want both the largeTask and the thumbTask to finish uploading the image, return the downloadURLs for each, and THEN update the firestore document with the download URLs.

startUpload(results) {
  // New image id applied to each incoming image
  const imageId = this.afs.createId();

  // Thumbnail Tasks
  const thumbPath = `${path}/${imageId}_small.jpg`;
  const thumbTaskRef = this.storage.ref(thumbPath);
  const thumbTask = this.storage.upload(thumbPath, results.thumb);

  // Large Image Tasks
  const largePath = `${path}/${imageId}_large.jpg`;
  const largeTaskRef = this.storage.ref(largePath);
  const largeTask = this.storage.upload(largePath, results.original);


  largeTask
    .snapshotChanges()
    .pipe(
      finalize(async () => {
        const thumbnailImageDownloadURL = await lastValueFrom(thumbTaskRef.getDownloadURL());
        const largeImageDownloadURL = await lastValueFrom(largeTaskRef.getDownloadURL());

      const images = {
        large_url: largeImageDownloadURL,
        small_url: thumbnailImageDownloadURL,
      };

      const newDocId = this.afs.createId();

      // this part should be after largeTask & thumbTask have completed, not just within `largeTask`
      return this.afs
        .doc(`${path}/${someID}/images/${newDocId}`)
        .set(images, { merge: true })
        .then(() => {
          // some other logic for later
           
        });
    })
  )
  .subscribe();

CodePudding user response:

Hi try this Function to Upload you Pictures and set the Image URL when the fork join worked trough all the subscribtions.

  uploadPostPictures2(event, postId: string) {
    const file = event.target.files[0];
    const filePath = 'PostPictures/'   this.userId   '/'   Date.now().toString();
    const fileRef = this.afStorage.ref(filePath);
    const task = this.afStorage.upload(filePath, file);
    this.uploadPercent = task.percentageChanges();
    return task.snapshotChanges();
  }
  
  startUpload() {
    const large: any;
    const small: any;
    forkJoin(this.uploadPostPictures2(large, '1'), 
    this.uploadPostPictures2(small, '1')).subscribe(res => {
       this.afs.collection('posts').doc(postId).update({photoUrl: 
       res.getDownloadURL()});
      });
    });
  }

Just change the Paths and Collections

  • Related