Angular2 Base64 sanitizing unsafe URL value
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.
Solution 1:
You would need
bypassSecurityTrustResourceUrl(html);
instead of
bypassSecurityTrustHtml(html);