首页 > 解决方案 > Display image from API

问题描述

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

enter image description here

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

enter image description here

标签: javascriptangulartypescript

解决方案


尝试这个

步骤1

删除Content-Type标题并设置responseTypeblobin httpOptions,但不像您那样在标题部分中。现在,您应该得到一个 blob 作为响应。之前,Angular 试图将您的响应解析为 JSON,因此出现错误

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);
  }

步骤 #2使用baseImage代替baseImage.image(响应是一个 blob,它没有image属性),然后使用createObjectURL从 blob 中获取图像 url。像你一样清理那个 URL

    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);
      }
    );

推荐阅读