[英]get image from backend api and display in angular
我想在 angularV10 中显示图像并从后端获取它,我不知道为什么图像不显示并出现错误我正在寻找如何解决但我没有得到答案请有人指导我
后端:
get_image:async(req,res,next)=>{
Image.findAll().then(data=>{
res.send(data)
}) }
api:
router.get("/get_image",uploadController.get_image)
前端Angular:service.ts
get_file(): Observable<any>{
return this.http.get(baseUrl + '/get_image' , { responseType: 'Blob' as 'json' })}
代码:
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result; <<< this.imageToShow
}, false);
if (image) {
reader.readAsDataURL(image);
console.log(image)
}
}
get_image():void{
this.AddFileService.get_file().subscribe(data=>{
this.createImageFromBlob(data);
console.log(data)
})}
html:
<img [src]="imageToShow "/>
错误:
大错误
unsafe:data:application/json;base64, ..... alot of chars i don't under stand
这方面的细节不多,但希望我至少可以为你澄清一些事情,这样你就可以更好地解决这个问题。
您不理解的许多字符是图像的 base64 编码字符串(如果您的代码正在生成图像,至少是适当的)。
您想要显示为图像的是一个数据 URI ,它看起来很像您所显示的:
data:image/jpeg;base64,[a lot of characters]
根据实际图像类型,它可能不是image/jpeg
,它可能是image/png
等。
您显示的最后一个块有两个问题:
unsafe:data:application/json;base64, ..... alot of chars i don't under stand
第一个,现在告诉你它应该是什么样子,它认为数据是application/json
而不是预期的image/xyz
。 因此,您构建该数据 URI 的过程在某处是错误的。 我怀疑您在 blob 类型中所说的应该是 json (因此, application/json
):
get_file(): Observable<any>{
return this.http.get(baseUrl + '/get_image' , { responseType: 'Blob' as 'json' })}
第二个是您真正看到的主要问题的线索: unsafe:...
为了以这种方式在 Angular 中显示图像,您需要通过DomSanitizer
放置这些 URI 和其他内容:
constructor(private readonly sanitizer: DomSanitizer) {}
public safeImage: SafeUrl;
private getImage(...): void {
const imageBase64String = this.createImageFromBlobOrSomething(...);
this.safeImage = this.sanitizer.bypassSecurityTrustUrl(imageBase64String);
}
然后您的模板将使用safeImage
代替:
<img [src]="safeImage"/>
这将停止unsafe:...
错误,但随后您会发现您看不到图像,因为数据 URI 用于application/json
,而不是图像类型,您需要提前 go并修复。
编辑:我对多个图像的方法是保存图像(如果你想保留初始图像以供进一步使用/操作)或者只保存它们的安全 url 版本......
this.rawImages = data; // Wherever your images come from, and if you want to keep them...
this.safeImages = [];
this.rawImages.forEach((img) => {
this.safeImages.push(this.sanitizer.bypassSecurityTrustUrl(img));
});
然后代替*ngFor
原始图像本身,而是在safeImages
数组上执行:
<div *ngFor="let safeUrl of safeImages">
<img [src]="safeUrl">
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.