Wednesday, April 4, 2018

Working with Base64 Decoded Image in Angular

We can save images in base64 encoded format in database. It has it's own advantages and disadvantages. But while loading those images in Angular Application, based on different factors like Content Security Policy etc, Angular does not allow to load base64 encoded images in the HTML. It will append unsafe to the url, as a result the HTML does not show the image properly.

For instance if I want to show the following image which is in base64.


I will have something similar in the HTML

<p><img src="data:image/jpeg;base64,/aaaiskk....></p>
But due to Content Security policy Angular will not load the above URL. And if you see the source then you will see that unsafe is appended before the base64 URL.

One way to workout in Angular is to Sanitize the URL so that Angular can load the URL. For that we can import DomSantitizer from @angular/platform-browser.

//Angular Controller
import {DomSanitizer} from '@angular/platform-browser';
export class Base64ImageComponent implements OnInit{
  constructor(private sanitizer: DomSanitizer) { }
  sanitize(url: string) {
    //return url;
    return this.sanitizer.bypassSecurityTrustUrl(url);
//Template HTML
<img [src]="sanitize(filePreview)"/>

A example plunker with full code can be found here

No comments :

Post a Comment