angularfire2上传后显示图像

时间:2018-06-02 20:02:39

标签: javascript firebase-storage angularfire2

使用Example Usage中的示例代码。我能够成功上传图像文件并显示链接。但是,我想在上传后立即将图像显示在img标签中,而不是链接到它。我怎么做到这一点?我尝试过这样的事情无济于事:

  profileUrl: Observable<string | null>;

  ....


  const task = this.storage.upload(path, file);
  const ref = this.storage.ref(path);
  this.uploadPercent = task.percentageChanges();
  console.log('Image uploaded!');

  task.snapshotChanges().pipe(
    finalize(() => this.downloadURL = this.profileUrl = ref.getDownloadURL())
  )
  .subscribe();

在我的模板文件中:

<img [src]="profileUrl | async" />

所有这些都来自示例,但我需要将Example UsageDownload Files部分合并。

2 个答案:

答案 0 :(得分:0)

我明白了。您无法订阅快照,但可以下载参考。

  const task = this.storage.upload(path, file);
  const ref = this.storage.ref(path);
  this.uploadPercent = task.percentageChanges();
  console.log('Image uploaded!');
  task.snapshotChanges().pipe(
    finalize(() => {
      this.downloadURL = ref.getDownloadURL()
      this.downloadURL.subscribe(url => (this.image = url));
    })
  )
  .subscribe();

答案 1 :(得分:-1)

我最近做了类似的事情。我的任务是上传图像,然后使该图像显示在用于上传图像的同一页面上。我在上传&#39;上写了WebAPI。服务器和此示例不使用angular2fire,因此在angular2fire订阅响应中,您将绑定变量更新为[src]。

HTML:

<img *ngIf="uploaded" [src]="myURL"> 

TS:

uploadedImage = "savedNameOfUploadedFile.png";
uploaded = false;
myURL = '';
uploadImage(){
    this._httpClient.post(this.apiEndPoint + '/imageupload', formdata)
    .subscribe(
        data => {
            this.uploaded = true;
            this.myURL = 'http://locationOfFileServer/' + this.uploadedImage;
          },
        error => { console.log(error); }
    );
}

我的代码要复杂得多,但这是一个简化版本以提高可读性。我使用了BehaviorSubject与我的上传服务和我的视图组件进行通信,但就像我说这是一个简化版本以提高可读性。如果您需要更多详细信息,请通知我,我将复制/粘贴我的生产代码。