代码之家  ›  专栏  ›  技术社区  ›  Jonathan

AngularFire2上传后显示图像

  •  0
  • Jonathan  · 技术社区  · 7 年前

    使用中的示例代码 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" />
    

    所有这些都来自于示例,但我需要结合 示例用法 Download Files 章节。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Jonathan    7 年前

    我想出来了。您不能订阅快照,但可以订阅下载引用。

      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
  •  -1
  •   user3777549    7 年前

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