在Angular 5中显示从后端发送的图像

时间:2018-06-04 08:28:08

标签: angular

我正在研究MEAN Stack应用程序,我想要做的是在HTML5的图像标记中显示用户的个人资料图像,因此图像保存在MongoDB和后面-end是Node

这是节点代码:

router.get('/getProfileImageok',(req,res)=>{
    gfs.files.findOne({ metadata: req.de },(err,file)=>{
      if(!file || file.length === 0){
        res.json({success:false,message:'no file exits'});
        console.log(req);
      }
      if(file.contentType === 'image/jpg' ||file.contentType === 'image/jpeg' || file.contentType === 'image/png'){
        const readStream = gfs.createReadStream(file.filename);
        readStream.pipe(res);
        console.log(req.decoded.userId);
      }else{
        res.json({success:false,message:'no image type'});
      }
    });
  });

这是**service.ts**

中Angular 5中的代码
getProfileImage(){
this.createAuthenticationHeaders(); // Create headers before sending to API
 this._http.get.(this.domain + '/authentication/getProfileImageok',this.options);
}

这是Angular 5中的代码

    image;
imageToShow="https://static1.squarespace.com/static/503935e6e4b011773393f0f9/t/52934b61e4b023ca75614a20/1385384808083/Facebook+User.gif";
        getImageFromService() {
              this.authService.getProfileImage().subscribe(data => {
                 this.image = data.arrayBuffer();
              }, error => {
                this.isImageLoading = false;
                console.log(error);
              });
        }

HTML中的代码

  <img [src]="imageToShow || image" alt="" class="img">

`

我更改代码后使用chrome devtool

the is the result

1 个答案:

答案 0 :(得分:0)

尝试类似:

const reader = new FileReader();
      reader.onload = (e: any) => {
        this.imageToShow = this.sanitizer.bypassSecurityTrustResourceUrl(e.target.result);
      };
      reader.readAsDataURL(imgReturnedFromBackend);