【问题标题】:angularfire2 Display Image after uploadangularfire2 上传后显示图片
【发布时间】:2018-11-12 14:46:33
【问题描述】:

使用来自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 部分结合起来。

【问题讨论】:

    标签: javascript firebase-storage angularfire2


    【解决方案1】:

    我想通了。您不能订阅快照,但您可以订阅下载参考。

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

    【讨论】:

    • 嘿,我在看到你想通之前回复了我的第一个答案。
    【解决方案2】:

    我最近做了这样的事情。我的任务是上传一张图片,然后让该图片出现在用于上传图片的同一页面上。我在“上传”服务器上编写了 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 与我的上传服务和我的视图组件进行通信,但就像我说的那样,这是一个简化版本以提高可读性。如果您需要更多详细信息,请告诉我,我将复制/粘贴我的生产代码。

    【讨论】:

    • 感谢您的评论,但这并不能真正帮助我修改使用 angular2fire 的代码以使其正常工作。你刚刚发布了完全不同的代码,可以完成类似的事情。
    • 1.在将图像文件发布到上传服务器之前,将带有 extsion 的图像名称保存在一个变量中,在我的示例中,我声明了一个“uploadedImage”变量来存储图像名称。 2. 在订阅响应中,将 html *ngIf=uploaded 设置为 true,使图像可见。 3.在订阅响应事件中设置图片src(你知道文件服务器的URL,所以连接步骤1中保存的名称并将其用作图片src URL)。 4. Angular 变化检测会将 img 标签更新为可查看,并使用您在步骤 3 中设置的 URL 作为图像 src。 5. 这适用于任何角度环境。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2013-03-28
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多