javascript - Display image from API
问题描述
I got problem how to display image send by API from backend it not display. And when I console.log
, I got this error.
This is my code as your reference.
HTML
<img [src]="imageToShow" style="width:100%;margin-left: -14px;">
Component
ngOnInit() {
this.getBanner()
}
getBanner() {
this.bannerId = {
confId: 1,
type: "Banner",
};
this.httpService.getBanner(this.bannerId).subscribe(
(baseImage: any) => {
let objectURL = "data:image/jpeg;base64," + baseImage.image;
this.imageToShow = this.sanitizer.bypassSecurityTrustUrl(objectURL);
},
(error) => {
// this.isImageLoading = false;
console.log(error);
}
);
}
Service
public getBanner(data){
console.log(data)
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
responseType: 'blob',
Authorization: 'Bearer '+this.getToken()
})
};
return this.httpClient.post((this.serverUrl + this.basePath + '/landing/conferenceitem'),data,httpOptions);
}
edit
when I check up Network Response
I got this image
解决方案
尝试这个
步骤1
删除Content-Type
标题并设置responseType
为blob
in httpOptions
,但不像您那样在标题部分中。现在,您应该得到一个 blob 作为响应。之前,Angular 试图将您的响应解析为 JSON,因此出现错误
public getBanner(data){
console.log(data)
const httpOptions = {
headers: new HttpHeaders({
Authorization: 'Bearer '+this.getToken()
}),
responseType: 'blob'
};
return this.httpClient.post((this.serverUrl + this.basePath + '/landing/conferenceitem'),data,httpOptions);
}
步骤 #2使用baseImage
代替baseImage.image
(响应是一个 blob,它没有image
属性),然后使用createObjectURL
从 blob 中获取图像 url。像你一样清理那个 URL
this.httpService.getBanner(this.bannerId).subscribe(
(baseImage: Blob) => {
let objectURL = URL.createObjectURL(baseImage);
this.imageToShow = this.sanitizer.bypassSecurityTrustUrl(objectURL);
},
(error) => {
// this.isImageLoading = false;
console.log(error);
}
);
推荐阅读
- wordpress-rest-api - WP REST Api 将帖子发布到远程 wordpress 网站
- php - 在另一个'中使用“with()”获取特定列
- python - Python - Dataframe - 将列数据拆分为新列 - 解释一些代码的含义
- php - 如何在 PHP 登录脚本中验证来自 SQL 的串联?
- xml - 未能检索到正确的节点数据
- mysql - 如何在mysql中将点添加到多边形或几何的所有点?
- python - Python 3.7 导入命令出现奇怪的 Pylint 错误
- ios - MKAnnotationView:在 annotationView 下方有文本并渲染 View
- javascript - 基于参数的单例模式在javascript中创建promise
- html - 根据元素数量调整元素大小