nadhem
nadhem

Reputation: 188

Angular 2 : display binary image served with express js

I have an image in the server and I want to send it to the client : here is my server side code :

var options = {
    root: './Images/',
    dotfiles: 'deny',
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true
    }
};
var fileName = "a.png";
BillModel.getBillsModel((err, config_model) => {
    if (err) {
        console.log("error from database " + err)
        //res.json({ code: 0, error: err, response: null })
    } else {
        res.sendFile(fileName, options, function (err) {
            if (err) {
                console.log(err);
            } else {
                console.log('Sent:', fileName);
            }
        });
   }

and here my code in the client side :

    this.billsService.getAllModel().subscribe(
      (data) => {
        console.log(data.text());
        this.image = data.text();
      },  
      (err) => console.log(err),
      () => console.log("Done")
    );

html code :

<img  src="'data:image/jpeg;base64,'+image"/>

So image binary data is successfully displayed in the console but i can't add it to the html page

solution : thanks to Lyubimov Roman , I have solved my issue using blob object and here is my code :

sertvice ts :

public getImage() {
    const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    let options = new RequestOptions({
      headers, responseType: ResponseContentType.Blob,
    });
    return this.http.get('http://localhost:3000/BillsModel/all', options)
      .map((res: Response) => { return (res); })
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

app component ts

this.billsService.getAllModel().subscribe(
      (data) => {
        console.log(data._body);
        var blob = new Blob([data.blob()], { type: "image/png" });
        var reader = new FileReader();

        reader.onload = (event) => {
          this.URL = reader.result;
        }
        reader.readAsDataURL(blob);
      },  //changed
      (err) => console.log(err),
      () => console.log("Done")
    );

html code :

 <img *ngIf="URL" [src]="URL" /> //you need to use *ngIf="URL" , otherwise some browser error could appear 

and the same back end code

Upvotes: 1

Views: 8027

Answers (2)

Lyubimov Roman
Lyubimov Roman

Reputation: 1269

You need to set responseType to blob and then fetch data by reader. Look here to make blob and here to recieve an image base64 content.

Upvotes: 2

PerfectPixel
PerfectPixel

Reputation: 1968

If you want to bind a base64 encoded image that you received from the server via angular bindings to the DOM. You need to trust the URL first, otherwise the DomSanitizer will remove it (see the docs).

url = sanitizer.bypassSecurityTrustUrl('data:image/jpeg;base64,' + image)

Then you can use that url and bind it: <img [src]="url">.

Upvotes: 0

Related Questions