Abdol Seed
Abdol Seed

Reputation: 1427

Pipe for returning Base64 version of image URL Angular 6

I have an angular 6 application and in some part of html codes, I`m showing images in Base64 format. For doing that I created a pipe for returning Base64 version of data that I send to the pipe. This is my pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'base64Imag',
})

export class Base64ImagPipe implements PipeTransform {
    transform(value: any, args?: any): any {
    let Base64 = BASE_LIBRARY_CODES;

    if (typeof(value) != 'undefined') {
       return Base64.encode(value);
    }else{
       return '';
    }   
  }
}

But it returns this:

<img src="unsafe:data:image/svg+xml;.....">

How can I fix "unsafe" in pipe?

Upvotes: 2

Views: 5304

Answers (2)

Abdol Seed
Abdol Seed

Reputation: 1427

This is the the way I found and works with help of friends here:

Pipe:

transform(value: any, args?: any) {
    if (typeof(value) != 'undefined') {
       return 'data:image/svg+xml;base64,' + btoa(value);
    }else{
       return '';
    }   
}

In component:

import { DomSanitizer } from '@angular/platform-browser';
constructor(public _DomSanitizer: DomSanitizer) { }

In html code:

<img width="50" [src]="_DomSanitizer.bypassSecurityTrustUrl(SVG_URL | base64Imag)">

Upvotes: 2

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11398

Your transform should use the DomSanitizer

import { Pipe, PipeTransform } from '@angular/core';
import { SafeUrl, DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'base64Imag',
})

export class Base64ImagPipe implements PipeTransform {

    constructor(private domSanitizer: DomSanitizer) {}

    transform(value: any, args?: any): SafeUrl {
    let Base64 = BASE_LIBRARY_CODES;

    if (typeof(value) != 'undefined') {
       return this.domSanitizer.bypassSecurityTrustUrl(Base64.encode(value));
    }else{
       return this.domSanitizer.bypassSecurityTrustUrl('');
    }   
  }
}

WARNING: calling this method with untrusted user data exposes your application to XSS security risks!

Upvotes: 1

Related Questions