首页 > 解决方案 > 从后端动态接收未知文件类型的图像

问题描述

亲爱的 Stackoverflow 用户,

我最近得到了将图像从后端动态加载到我的应用程序中的要求。直到最近——因为它从未在文档中以任何其他方式指定或其他方式——我认为我们总是 SVG 图像。这花费了很大的精力,因为我有一个粗略的想法,该做什么开始。

getGmaLogo(gmaId) {

this.httpClient.get(ApiUrls.QA_GMA_LOGO + "/" + gmaId, { headers: this.authHeader, responseType: "text" })
  .pipe(catchError(error => {
  // Those are merely my own error messages 
    this.errorService.showError(error);
    return this.errorService.handleError(error);
  }))
  .subscribe(image => {         

    let base64EncodedString = window.btoa(image)

    this.gmaLogo = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/svg+xml;base64,' + s);
  })

}

然后像这样将它添加到我的页面中。

<img [src]="gmaService.gmaLogo || ''" alt="Company Name"/>

但是,唉,事情永远不会变得容易,不是吗?

其实我可能会收到jpeg、png等。显然,如果他们不得不满足于仅使用 SVG 的图标,这会给人们带来不便。这导致了我的问题......我可以从收到的响应中动态推断出我有什么可用的数据类型,而无需在标题中设置特定的响应类型?将其留空是行不通的,因为我们知道,默认的响应类型是 JSON。

标签: javascriptangulartypescript

解决方案


在我的项目中,我Blob在客户端使用响应类型,并不关心文件的类型。这按预期工作:https ://stackblitz.com/edit/angular-yuy5km

服务

getGmaLogo(imageUrl: string): Observable<Blob> {
  return this.httpClient.get(imageUrl, {headers: this.authHeader, responseType: 'blob' });
}

零件

为了从 Blob 创建图像,我曾经FileReader读取Blob

imageToShow: any;

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

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

接下来,您从服务中获取图像

getImageFromService() {
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
      }, error => {
        console.log(error);
      });
}

HTML

<img [src]="imageToShow" />

推荐阅读