使用angularfire将文件上传到firebase存储

uploading file to firebase storage using angularfire

我正在使用 angularfire2 将图像上传到 firebase 存储。上传工作正常,但我在等待下载代码 url 可用的时间上遇到了麻烦。这是选择文件时的代码

 async onFilesAdded(event){
      console.log("file added")
      if (event.target.files.length > 0) {
        const file = event.target.files[0];
        console.log("File name is:" + file.name)

         await this.dataSvc.pushUpload(file).then(
            (res) => {
              console.log("download url is::" + this.dataSvc.downloadURL)
            },
            (err) => console.log("fail to upload file:" + err)
          )


      }
    }

我的服务实现如下

 pushUpload(file: File) {
    const filePath = '/' + file.name;
    const fileRef = this.storage.ref(filePath);

    return new Promise<any>((resolve, reject) => {
         const task = this.storage.upload(filePath, file);

          task.snapshotChanges().pipe(
      finalize(() => this.downloadURL = fileRef.getDownloadURL() )
   ).subscribe(
        res => resolve(res),
        err => reject(err))
   }
   )
  }

我希望等到 promise 得到解决并且我看到下载 url。但是我的代码似乎没有等待,我得到了未定义的 downloadUrl,几秒钟后下载 url 实际上出现在服务中。所以基本上我调用 pushUpload 的代码不会等待下载完成。

我从未在 finalize

中下载 url 的另一种变体
pushUpload(file: File) {
    const path = '/' + file.name;
    const ref = this.storage.ref(path);

    let task = this.storage.upload(path, file);
    let snapshot   = task.snapshotChanges().pipe(
      finalize( async() =>  {
        this.downloadURL = await ref.getDownloadURL().toPromise();
        console.log("download url i got is:" + this.downloadURL)
      }),
    );
  }

下载似乎正确完成。但是你用 snapshotChanges 可观察到的第一个发射值解决了你的承诺,它没有 属性 downloadURL 因此未定义的结果。

您应该订阅 fileRef.getDownloadURL() observable 以获得您的 URL。

pushUpload(file: File) {
    const filePath = '/' + file.name;
    const fileRef = this.storage.ref(filePath);

    return new Promise<any>((resolve, reject) => {
        const task = this.storage.upload(filePath, file);

        task.snapshotChanges().pipe(
            finalize(() => fileRef.getDownloadURL().subscribe(
                res => resolve(res),
                err => reject(err));
            )
        ).subscribe();
    })
}

使用 promise 方法的代码看起来有点难看。我不知道你是否可以在订阅内订阅,我以前没有这样做过。

一旦 snapshotChanges observable 完成 finalize 操作触发并订阅 fileRef.getDownloadURL() observable,该 observable 应立即发出 URL 并解决承诺.

而且我建议使用可观察对象而不是创建新的承诺。