admin管理员组

文章数量:1355643

I got problem how to display image send by API from backend it not display. And when I console.log, I got this error.

This is my code as your reference.

HTML

<img [src]="imageToShow" style="width:100%;margin-left: -14px;">

Component

ngOnInit() {
  this.getBanner()
}

    getBanner() {
        this.bannerId = {
          confId: 1,
          type: "Banner",
        };
        this.httpService.getBanner(this.bannerId).subscribe(
          (baseImage: any) => {
            let objectURL = "data:image/jpeg;base64," + baseImage.image;
            this.imageToShow = this.sanitizer.bypassSecurityTrustUrl(objectURL);
          },
          (error) => {
            // this.isImageLoading = false;
            console.log(error);
          }
        );
      }

Service

public getBanner(data){
    console.log(data)
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        responseType: 'blob',
        Authorization: 'Bearer '+this.getToken()
      })
    };
    return this.httpClient.post((this.serverUrl + this.basePath + '/landing/conferenceitem'),data,httpOptions);
  }

edit

when I check up Network Response I got this image

I got problem how to display image send by API from backend it not display. And when I console.log, I got this error.

This is my code as your reference.

HTML

<img [src]="imageToShow" style="width:100%;margin-left: -14px;">

Component

ngOnInit() {
  this.getBanner()
}

    getBanner() {
        this.bannerId = {
          confId: 1,
          type: "Banner",
        };
        this.httpService.getBanner(this.bannerId).subscribe(
          (baseImage: any) => {
            let objectURL = "data:image/jpeg;base64," + baseImage.image;
            this.imageToShow = this.sanitizer.bypassSecurityTrustUrl(objectURL);
          },
          (error) => {
            // this.isImageLoading = false;
            console.log(error);
          }
        );
      }

Service

public getBanner(data){
    console.log(data)
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        responseType: 'blob',
        Authorization: 'Bearer '+this.getToken()
      })
    };
    return this.httpClient.post((this.serverUrl + this.basePath + '/landing/conferenceitem'),data,httpOptions);
  }

edit

when I check up Network Response I got this image

Share Improve this question edited May 24, 2020 at 18:52 Pravu asked May 24, 2020 at 18:43 PravuPravu 6081 gold badge10 silver badges31 bronze badges 7
  • Are you sure the API response is JSON? – Aluan Haddad Commented May 24, 2020 at 18:46
  • I think the API is returing error . It is not at all going to success block . – Harmandeep Singh Kalsi Commented May 24, 2020 at 18:47
  • The api is returning binary, you can convert it to base64 – Adam Mudianto Commented May 24, 2020 at 18:47
  • check my answer below. – Aakash Garg Commented May 24, 2020 at 18:52
  • When I checkup Network response I got image... Refer my question – Pravu Commented May 24, 2020 at 18:53
 |  Show 2 more ments

3 Answers 3

Reset to default 4

Try this

Step #1

Remove Content-Type header and set responseType to blob in httpOptions, but not in the header part like you did. Now, you should get a blob as a response. Before, angular was trying to parse your response as JSON, hence the error

public getBanner(data){
    console.log(data)
    const httpOptions = {
      headers: new HttpHeaders({
        Authorization: 'Bearer '+this.getToken()
      }),
       responseType: 'blob'
    };
    return this.httpClient.post((this.serverUrl + this.basePath + '/landing/conferenceitem'),data,httpOptions);
  }

Step #2 Use baseImage instead of baseImage.image (the response is a blob, it does not have an image property), and then use createObjectURL to get an image url from the blob. Sanitize that URL like your did

    this.httpService.getBanner(this.bannerId).subscribe(
      (baseImage: Blob) => {

       let objectURL = URL.createObjectURL(baseImage);       
        this.imageToShow = this.sanitizer.bypassSecurityTrustUrl(objectURL);

      },
      (error) => {
        // this.isImageLoading = false;
        console.log(error);
      }
    );

One way to fix this is by Setting the response type to blob

const requestOptions: Object = {
/* other options here */
responseType: 'blob'
}

return this.httpClient.post((this.serverUrl + this.basePath + '/landing/conferenceitem'),data,requestOptions); 

and you have to convert your image data to a dataURL:

   this.httpService.getBanner(this.bannerId).subscribe(
      (baseImage: any) => {
         this.imageToShow = baseImage;
      },
      (error) => {
        // this.isImageLoading = false;
        console.log(error);
      }
    );

Change Your getBannerMethod as below :-

getBanner() {
        this.bannerId = {
          confId: 1,
          type: "Banner",
        };
        this.httpService.getBanner(this.bannerId).subscribe(
          (baseImage: any) => {
            const reader = new FileReader();
            const url = reader.readAsDataURL(baseImage.image);
            reader.onloadend = () => this.imageToShow = reader.result;
          },
          (error) => {
            // this.isImageLoading = false;
            console.log(error);
          }
        );
      }

Working Stackblitz :- https://stackblitz./edit/angular-yvicvq

本文标签: javascriptDisplay image from APIStack Overflow