1

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

nadhem
  • 178
  • 4
  • 20
  • I guess you should set responseType to blob and then fetch data by reader. Look [here](https://stackoverflow.com/a/39690808/2918518) to make blob and [here](https://stackoverflow.com/a/18650249/2918518) to recieve an image base64 content. – Lyubimov Roman Aug 13 '17 at 17:07
  • 1
    thanks @LyubimovRoman , it's done with blob , I wish you have post it as answer and not comment – nadhem Aug 13 '17 at 18:28

2 Answers2

2

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.

Lyubimov Roman
  • 1,269
  • 15
  • 27
  • Please include the actual code instead of just links...in case the links become dead in the future – ganders Jun 21 '18 at 14:15
0

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">.

PerfectPixel
  • 1,918
  • 1
  • 17
  • 18