55

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.

2 Answers 2

68

You would need

bypassSecurityTrustResourceUrl(html);

instead of

bypassSecurityTrustHtml(html);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That was my mistake.
I also recommend you enable pure:true for you pipe
-2

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.