Angular2 Base64 sanitizing unsafe URL value
AngularAngular Problem Overview
Response from my server looks like following:
[{"coreGoalId":1,"title":"Core goal 1","infrastructure":"Sample Infrastructure","audience":"People","subGoals":null,"benefits":[{"benefitId":1,"what":"string","coreGoalId":1}],"effects":null,"steps":null,"images":[{"imagelId":1,"base64":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcU\nFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo\nKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wgARCAIWAe4DASIA\nAhEBAxEB/8QAHAABAAIDAQEB"}]}]
I am trying to display the base64 image returned in it.
In my component:
ngOnInit() {
this.homeService.getGoals()
.subscribe(
goals => this.coreGoals = goals,
error => this.errorMessage = <any>error);
}
and then in template:
<ul>
<li *ngFor="let goal of coreGoals">
{{goal.title}}
<img [src]="'data:image/jpg;base64,'+goal.images[0].base64 | safeHtml" />
</li>
</ul>
Where safeHtml is a Pipe I created like following:
import { Pipe } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name: 'safeHtml'})
export class SafeHtml {
constructor(private sanitizer:DomSanitizer){}
transform(html) {
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
This gives me Required a safe URL, got a HTML
error. What is going wrong here? If I remove the pipe from <img />
then it says unsafe url.
Angular Solutions
Solution 1 - Angular
You would need
bypassSecurityTrustResourceUrl(html);
instead of
bypassSecurityTrustHtml(html);
Solution 2 - Angular
I had the same issue. Our application 'X' used to store locally uploaded images by converting them to base64 before saving it to the database(We used to pop the intial data i.e data:image/jpg;base64). While recovering it to display, I had the same issue. I used to concat the popped data to the recovered base64 string. It used to throw the above error. So, we decided to store the entire converted string without popping it and now its working fine. See, if it helps!