Firebase存储多张照片上传问题

时间:2020-03-12 13:16:45

标签: angular typescript firebase firebase-storage

我正在尝试将多张照片上传到我的Firebase存储中。由于某些原因,它会继续覆盖原始上载,而不是使用venueID属性创建文件夹。有人可以在这里发光吗?

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);
    }
}

1 个答案:

答案 0 :(得分:2)

问题在于,所有图片在消防桶内共享同一位置。因为您在forEach之前设置了位置路径。

下面的代码应创建场所/照片/地点ID /您的图片

  // 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;
  }
}