MrRobot
MrRobot

Reputation: 1167

Firebase Storage Multiple photo Upload Issue

I'm trying to upload multiple photos to my Firebase Storage. For some reason it keeps overwriting the original upload, and it's not creating the folder with the venueID property. Can anybody shine a light here?

main.ts

async localPictureUpload(): Promise<any> {
    // Checks if there is something to be uploaded.
    if (this.photosToUpload.length > 0) {
        const location = `venues/photos/${this.venueID}/`;
        // photosToUpload is an array containing base64 strings.
        this.photosToUpload.forEach(async photoElement => {
            const randomID = this.venueService.createID();
            await this.uploadService.uploadFile(photoElement, location, true)
                .then(async data => {
                    const urlData = await data.ref.getDownloadURL();
                    const photoObject: Photo = {
                        fileName: `${this.venueID}${randomID}`,
                        url: urlData,
                        uploadedBy: this.currentUserID
                    };
                    await this.venueService.addPhoto(this.venueID, photoObject);
                },
                (err) => console.error(err));
        });
    } else {
        return;
    }
}

upload.service

uploadFile(file: any, path: string, base64?: boolean) {
    if (base64) {
        return this.uploadDB.ref(path).putString(file, 'data_url');
    } else {
        return this.uploadDB.upload(path, file);
    }
}

Upvotes: 0

Views: 51

Answers (1)

JS Lover
JS Lover

Reputation: 622

The problem is that all the pictures share the same location inside the firesotrage bucket. Because you setup the location path before the forEach.

This code below should create venues/photos/venueID/yourPictures

  // Checks if there is something to be uploaded.
  if (this.photosToUpload.length > 0) {
    // photosToUpload is an array containing base64 strings.
    this.photosToUpload.forEach(async photoElement => {
      const randomID = this.venueService.createID();
      const location = `venues/photos/${this.venueID}/${randomID}/`;
      // const location = `venues/photos/${this.venueID}/`; <---- The problem 
      //  const randomID = this.venueService.createID(); 
      await this.uploadService.uploadFile(photoElement, location, true)
        .then(async data => {
            const urlData = await data.ref.getDownloadURL();
            const photoObject: Photo = {
              fileName: `${this.venueID}${randomID}`,
              url: urlData,
              uploadedBy: this.currentUserID
            };
            await this.venueService.addPhoto(this.venueID, photoObject);
          },
          (err) => console.error(err));
    });
  } else {
    return;
  }
}

Upvotes: 2

Related Questions