如何从Angular中的服务器以角度渲染图像?

时间:2019-03-09 18:13:45

标签: angular

我有一个spring boot后端...提供了一个返回字节数组映像的服务.. 如何在Angular中接收它并呈现它...

这是我的角度代码:

array(3) {
    ["A"]=>
        array(3) {
            ["B"]=>
            string(4) "A->B"
            ["D"]=>
            string(4) "A->D"
            ["C"]=>
            string(4) "A->C"
      }
    ["B"]=>
        array(2) {
            ["D"]=>
            string(4) "B->D"
            ["C"]=>
            string(4) "B->C"
        }
    ["D"]=>
        array(1) {
            ["C"]=>
            string(4) "D->C"
       }
  }

我正在尝试console.log(),响应为200,但我收到错误消息:消息:“ http://localhost:8080/finance/api/getFile解析期间Http失败”

1 个答案:

答案 0 :(得分:1)

除非您指出期望使用其他响应类型,否则http客户端尝试将响应解析为JSON。对二进制数据使用responseType blob

this.http.post(_loadFileByIdUrl, fd, { responseType: 'blob' });

鉴于您的模板中有一个图像标签,例如:

<img #smartesImage />

然后您可以像这样访问模板中的图像

@ViewChild('smartesImage') smartesImage: ElementRef<any>;

并使用以下代码实际显示二进制数据:

this.http.post(_loadFileByIdUrl, fd, { responseType: 'blob'}).subscribe(res => {
   const objectURL = URL.createObjectURL(res);
   this.smartesImage.nativeElement.src = objectURL;
});