Angular 2 - render byte[] from Web Api as an image src

后端 未结 2 798
野的像风
野的像风 2020-12-04 18:46

I have an Angular 2 app that is connecting to a Web Api backend. There is an endpoint that returns a byte[] of an image that is stored in a sql database. How can I display t

2条回答
  •  忘掉有多难
    2020-12-04 19:04

    So the accepted answer by rinukkusu is very helpful & detailed but you don't have to:

    1- Neither make a directive (but you can of course)

    2- Nor to use the sanitizer service & make an sanitization exception

    I was a little bit overwhelmed by those two tasks, especially bypassing the sanitization, so I will write the simplest way to handle this safely

    You can simply use the following method (in generic way):

    1- Return the image from your backend as base64 encoded string

    2- Recieve that base64 string of the image in Angular 2+ & build the following string property in your typescript file then safely use it in your html directly without using the sanitizer service

    // so for example you will get the image for example in this dataService.ts
    
    this.http.get(this.api_url + 'image').subscribe(response => {
        this.image = response['image'];
        this.imageSrc = 'data:image/jpeg;base64,' + this.image;
    });
    

    Then in your html file , you can use the imageSrc property directly (for example from the injected dataService that have the property ready)

    
    

    I hope this helps someone else & many thanks for rinukkusu as his answer helped me personally

提交回复
热议问题