首页 > 解决方案 > Angular 6 - 上传后获取 Firebase 存储文件的下载 URL

问题描述

我在这里想要完成的是一个简单的想法。

  1. 将文件上传到 Firebase 存储

  2. 获取文件的链接并将其插入表单中。

问题是,我无法获取下载 URL。

当我上传某些东西时,它确实会上传,但我收到以下错误消息:

Object { code_: "storage/object-not-found", message_: "Firebase Storage: Object 'rnmgm3vvpz' does not exist.", serverResponse_: "{\n  \"error\": {\n    \"code\": 404,\n    \"message\": \"Not Found.  Could not get object\"\n  }\n}", name_: "FirebaseError" }

这是要在 component.ts 上上传的代码:

upload(event) {
  const id = Math.random().toString(36).substring(2);
  this.ref = this.afStorage.ref(id);
  this.task = this.ref.put(event.target.files[0]);
  this.uploadState = this.task.snapshotChanges().pipe(map(s => s.state));
  this.uploadProgress = this.task.percentageChanges();
  this.downloadURL = this.ref.getDownloadURL();
}

在 component.html 上:

<input type="file" (change)="upload($event)" accept=".png,.jpg" />

文件上传后如何获取downloadURL?

标签: angularfirebasegoogle-cloud-firestore

解决方案


您应该将 finalize() 添加到管道中,例如:

this.task.snapshotChanges().pipe(
  finalize(() => {
    this.downloadURL = this.ref.getDownloadURL(); // <-- Here the downloadURL is available.
  })
).subscribe();

在 finalize() 步骤中,downloadURL 可用,因此您可以从 ref 中异步获取他。 --UPDATE
您说您使用的是 Angular 6,所以我假设您使用的是最新版本的 firebase。
他们将 getDownloadURL() 从 Task 更改为 Observable,因此要获取实际的 URL,您只需订阅即可。

this.task.snapshotChanges().pipe(
  finalize(() => {
    this.ref.getDownloadURL().subscribe(url => {
      console.log(url); // <-- do what ever you want with the url..
    });
  })
).subscribe();

推荐阅读