我正在尝试在Angular2中显示来自Nodejs响应的图像。
节点:
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网址时,显示“图像”blob:http://localhost:4200/2a723d0c-da55-4bd5-84fd-4895c803c7a5“无法显示,因为它包含错误。” 那我在做错什么?
答案 0 :(得分: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);
}
});
});