Angular 5 - How to display image in HTML that comes as output from a http POST?

后端 未结 2 2012
心在旅途
心在旅途 2021-01-21 14:05

I need to display an thumbnail/image that comes from a POST request

Postman shows the output in right way

I\'m trying to use the same i

2条回答
  •  佛祖请我去吃肉
    2021-01-21 14:30

    With Suresh Kumar Ariya's help and after a lot of back/forth, found the solution.

    Solution was discussed here: https://github.com/angular/angular/issues/18586

    The key here is to use responseType: 'blob' as 'json' and not responseType: 'blob'

    Service.ts

    getBlobThumbnail(): Observable {
      console.log("....AzureblobService.getBlobThumbnail()");
      const headers = new HttpHeaders({
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    });
    
    return this.httpClient.post(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

    Thumbnail imageBlobUrl

    Environment: Angular 5.0.0

提交回复
热议问题