Angular 5-如何以HTML形式显示来自HTTP POST输出的图像?

时间:2018-10-09 00:30:39

标签: angular http post

我需要显示来自POST请求的缩略图/图像

邮递员以正确的方式显示输出

enter image description here

我试图在Angular组件中使用相同的控件,但不显示。控制台显示文本/二进制文件。

enter image description here

html

<img src="{{turl}}" />

Component.ts

 turl : any

getThumbnail() : void {
this.azureblobService.getBlobThumbnail()
  .subscribe(
    (val) => {
      console.log("POST call - getThumbnail- successful value returned in body",
        val);
      this.turl = val; //<====== Set value here
    },
    response => {
      console.log("POST call - getThumbnail - in error", response);
    },
    () => {
      console.log("The POST - getThumbnail - observable is now completed.");
    });
 }

服务

getBlobThumbnail() {
console.log("....AzureblobService.getBlobThumbnail()");
const headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'Accept' : 'application/json',
  'Ocp-Apim-Subscription-Key' : 'xxxxxxx'
});

return this.http.post(this.thumbnailFetchUrl,
  JSON.stringify({
    responseType: "blob",
    "url": "http://xxxx.blob.core.windows.net/acsazurecontainer/Git-Logo-1788C.png",
  }), {headers: headers});
}

需要任何帮助吗?

2 个答案:

答案 0 :(得分:1)

为了在DOM中显示图像,我们需要将blob转换为base64。这是代码

createImageFromBlob(image: Blob) {
   let reader = new FileReader();
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result;
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

此外,通过将safeurl应用于图片src,确保使用DomSanitizer可注入服务。

答案 1 :(得分:0)

Suresh Kumar Ariya's的帮助下,经过反复的摸索,找到了解决方法。

此处讨论了解决方案:https://github.com/angular/angular/issues/18586

此处的关键是使用responseType: 'blob' as 'json'而不是responseType: 'blob'

Service.ts

getBlobThumbnail(): Observable<Blob> {
  console.log("....AzureblobService.getBlobThumbnail()");
  const headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Accept': 'application/json',
});

return this.httpClient.post<Blob>(this.thumbnailFetchUrl,
  {
    "url": "http://xxxx/Logo-1788C.png"
  }, {headers: headers, responseType: 'blob' as 'json' });

}

Component.ts

getThumbnail() : void {
 this.azureblobService.getBlobThumbnail()
   .subscribe(
      (val) => {
        console.log("POST - getThumbnail- successful value returned in body", val);
        this.createImageFromBlob(val);
    },
    response => {
      console.log("POST - getThumbnail - in error", response);
    },
    () => {
      console.log("POST - getThumbnail - observable is now completed.");
    });
}
/* Convert */
createImageFromBlob(image: Blob) {
 console.log("Call createImageFromBlob()", image);
 let reader = new FileReader();
 reader.addEventListener("load", () => {
  this.imageBlobUrl = reader.result;
 }, false);

 if (image) {
  reader.readAsDataURL(image);
 }
}

Component.html

<h2>Thumbnail imageBlobUrl</h2>
<img [src]="imageBlobUrl">

环境:Angular 5.0.0