0

I have a simple cuestion. I have the following service in angular 4 app.

  getProviderPhoto(id:string){
    return this.http.get(this.apiUrl+"/"+id+"/images", {responseType: "blob"});
  }

I need to convert this Blob response to Image file to use the following method:

 createImageFromBlob(image: Blob) {
    let reader = new FileReader();
    this.photo = new File([image],"foto.png",{ type: 'image/png' });
    reader.readAsDataURL(this.photo);
    reader.onload = (event: any) => {
      this.image=event.target.result;
      console.log(this.image);
    }
 }

console.log

data:image/png;base64,ImlWQk9Sd.....

To use the downloaded image to show it in my html:

<div class="profile-image center" [ngStyle]="{ 'background-image': 'url(' + image + ')'}"></div>

On the other hand, if I do this, it works perfectly:

this.image="http://localhost:8083/v1/providers/"+this.id+"/images";

How can I get the same result but using Angular HttpClient.Get?

AlejoDev
  • 4,345
  • 9
  • 36
  • 67
  • 1
    `I've tried a thousand ways but I can not get it to work `? Really it's quite hard to fathom. See [this](https://stackoverflow.com/questions/45530752/getting-image-from-api-in-angular-4) and [this](https://stackoverflow.com/questions/7650587/using-javascript-to-display-blob) – Vikas May 15 '18 at 19:25
  • If you analyze my code you can see that I am based on the code of your first link, but I can not get it working, I am new working with angular – AlejoDev May 15 '18 at 20:22
  • What does the event.target.result variable return? Does it start with `data:image/png;base64,`? – Gosha_Fighten May 15 '18 at 21:01
  • Yes, it start with data:image/png;base64,the blob content, but if I deleted the line `this.photo = new File([image],"photo.png",{ type: 'image/png' });` of `createImageFromBlob` method it start with data:application/json;base64, – AlejoDev May 15 '18 at 21:10
  • 1
    This may be an issue with `DomSanitizer` preventing XSS when trying to set this specific background-image style property. You may need to use `bypassSecurityTrustStyle()`. See this [answer](https://stackoverflow.com/a/38663363/5059657) – Alexander Staroselsky May 15 '18 at 21:10
  • Thank you for your comment, but I do not get any error, just do not show the image – AlejoDev May 15 '18 at 21:17

0 Answers0