javascript - 从后端动态接收未知文件类型的图像
问题描述
亲爱的 Stackoverflow 用户,
我最近得到了将图像从后端动态加载到我的应用程序中的要求。直到最近——因为它从未在文档中以任何其他方式指定或其他方式——我认为我们总是 SVG 图像。这花费了很大的精力,因为我有一个粗略的想法,该做什么开始。
getGmaLogo(gmaId) {
this.httpClient.get(ApiUrls.QA_GMA_LOGO + "/" + gmaId, { headers: this.authHeader, responseType: "text" })
.pipe(catchError(error => {
// Those are merely my own error messages
this.errorService.showError(error);
return this.errorService.handleError(error);
}))
.subscribe(image => {
let base64EncodedString = window.btoa(image)
this.gmaLogo = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/svg+xml;base64,' + s);
})
}
然后像这样将它添加到我的页面中。
<img [src]="gmaService.gmaLogo || ''" alt="Company Name"/>
但是,唉,事情永远不会变得容易,不是吗?
其实我可能会收到jpeg、png等。显然,如果他们不得不满足于仅使用 SVG 的图标,这会给人们带来不便。这导致了我的问题......我可以从收到的响应中动态推断出我有什么可用的数据类型,而无需在标题中设置特定的响应类型?将其留空是行不通的,因为我们知道,默认的响应类型是 JSON。
解决方案
在我的项目中,我Blob
在客户端使用响应类型,并不关心文件的类型。这按预期工作:https ://stackblitz.com/edit/angular-yuy5km
服务
getGmaLogo(imageUrl: string): Observable<Blob> {
return this.httpClient.get(imageUrl, {headers: this.authHeader, responseType: 'blob' });
}
零件
为了从 Blob 创建图像,我曾经FileReader
读取Blob
imageToShow: any;
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
接下来,您从服务中获取图像
getImageFromService() {
this.imageService.getImage(yourImageUrl).subscribe(data => {
this.createImageFromBlob(data);
}, error => {
console.log(error);
});
}
HTML
<img [src]="imageToShow" />
推荐阅读
- winapi - 为什么来自 MS CryptoAPI 的 CryptDecrpyt() 不能正确解密远程系统上的前 16 个字节?
- css - 在 ionic 5 中设置背景图像
- reactjs - Create-react-app 绝对导入不适用于 yarn v2 工作区 + 打字稿
- mysql - 将多条记录的左连接表合并为一条记录mysql
- scala - 具有结构共享的数据结构转换
- java - 在 PreparedStatement 处获取 NullPointerException
- python - 从文件中读取文本并在 if 语句中使用
- node.js - 为什么模式字段没有使用节点 js 保存在数据库中
- jwt - 我如何添加授权:“JWT
“到 http 请求?在 Nuxt.js 中 - java - Resilience4j 使用 CompletionStage 重试