2016-12-03 108 views
1

我试图在Angular2中显示来自Nodejs响应的图像。Node.Js/Express + Angular2图像发送和显示图像

节点:

router.get('/users/avatar', function(req, res){ 
    res.sendFile(req.user.avatarName, { 
     root: path.join(__dirname+'/../uploads/') 
    }, function (err) { 
     if (err) { 
      console.log(err); 
     } 
    }); 
}); 

和Angular2

//userService.ts 
    getAvatar(): Observable<any>{ 
    return this.http 
     .get(this.protectedUrl +'/avatar', {headers: this.protectedHeaders}) 
     .map(res => { 
      return new Blob([res["_body"]], { 
      type: 'image/png' 
      }) 
     }).map(blob => { 
      let urlCreator = window.URL; 
      return this.sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob)); 
      }) 

    } 

app.component.ts

ngOnInit() { 
     this.userService.getAvatar().subscribe(response =>{ 
      console.log(response); 
      this.avatarSrc=response; 
     }); 
    } 

app.component.htm

<div> 
    <img [src]="avatarSrc"> 
<div> 

这不显示任何内容,但是我检查blob url,它显示“The image”blob:http://localhost:4200/2a723d0c-da55-4bd5-84fd-4895c803c7a5“无法显示,因为它包含错误。” 那么我在做什么错?

回答

0

使用Response#blob()方法来检索BLOB:

和Angular2

//userService.ts 
    getAvatar(): Observable<any>{ 
    return this.http 
     .get(this.protectedUrl +'/avatar', { 
      headers: this.protectedHeaders, 
      responseType: ResponseContentType.Blob 
     }) 
     .map(res => res.blob()) 
     .map(blob => { 
      let urlCreator = window.URL; 
      return this.sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob)); 
      }) 

    } 

节点:

在响应本身添加的内容类型:

router.get('/users/avatar', function(req, res){ 
    res.sendFile(req.user.avatarName, { 
     root: path.join(__dirname+'/../uploads/'), 
     headers: {'Content-Type': 'image/png'} 
    }, function (err) { 
     if (err) { 
      console.log(err); 
     } 
    }); 
}); 
+0

现在好了角度返回 错误:请求正文不是blob或ar蓝光缓冲器 –

+0

更新了答案,它缺少responseType选项 –