Angular 2:显示通过Express JS服务的二进制图像 [英] Angular 2 : display binary image served with express js

查看:56
本文介绍了Angular 2:显示通过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代码:

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

因此图像二进制数据已成功显示在控制台中,但我无法将其添加到html页面

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

解决方案::感谢 Lyubimov Roman ,我已经使用blob解决了我的问题对象,这是我的代码:

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

服务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'));
  }

应用程序组件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代码:

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

和相同的后端代码

推荐答案

您需要将responseType设置为blob,然后由读取器获取数据.在此处进行查找,并这里以接收图像base64内容.

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.

这篇关于Angular 2:显示通过Express JS服务的二进制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆