Sanitize URL in Angular 4 - Working with Base64 Images

Handling Images is a very common in most of the web applications. Typically we need to render image in a webpage (very common) and some times we need to provide an user interface to upload images, editing images etc.

We can save the uploaded image in the web application in multiple ways. For instance we can save images in base64 encoded format in database or we can save the uploaded images in file system on the server and store the image path in database. It has it's own advantages and disadvantages.

Angular applications sometimes does not show the image if the image is in base64 econdoed form. While loading base64 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.

data:image/png;base64,aaaiskkAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==

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 we see the HTML source of the page though browsers tools such as Inspect in Chrome or Page Source in Firefox 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 https://embed.plnkr.co/dGJDKH0ZfouNskRbZmFz/?show=preview%23%2Fitems%2FLH

Comments

  1. thanks for posting this, this was exactly i was facing. Is there any OOTB components that Angular provides to deal with this.

    ReplyDelete
    Replies
    1. I am not aware of any OOTB components that can do this.

      Delete
  2. your tutorial is a game-changer! Your in-depth explanation and practical examples illuminate the intricacies of handling decoded images. What Fastest Cryptocurrency Your expertise aids developers in effectively integrating and manipulating them.

    ReplyDelete

Post a Comment

Popular posts from this blog

Difference between volatile and synchronized

Converting Java Map to String

Masking Credit Card number in Java