加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular4显示来自服务器的图像

发布时间:2020-12-17 06:49:34 所属栏目:安全 来源:网络整理
导读:我想在img标签中显示图像: 我这样做 零件 this.file.url=this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.file.url)); 模板 img [src]="file.url" 我收到了这个错误 ERROR TypeError: Failed to execute 'createObjectURL' on 'URL
我想在img标签中显示图像:
我这样做

零件

this.file.url=this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.file.url));

模板

<img [src]="file.url">

我收到了这个错误

ERROR TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.

解决方法

您应该在GET-Request设置中设置responseType:ResponseContentType.Blob,因为这样您可以将图像作为blob获取并在以后转换为base64编码的源.你上面的代码不好.如果您想要正确执行此操作,请创建单独的服务以从API获取图像.因为在组件中调用HTTP-Request并不好.

这是一个工作示例:

创建image.service.ts并输入以下代码:

getImage(imageUrl: string): Observable<File> {
        return this.http
            .get(imageUrl,{ responseType: ResponseContentType.Blob })
            .map((res: Response) => res.blob());
    }

现在你需要在image.component.ts中创建一些函数来获取图像并在html中显示它.

要从Blob创建图像,您需要使用JavaScript的FileReader.
这是创建新FileReader并侦听FileReader的load-Event的函数.结果,此函数返回base64编码的图像,您可以在img src-attribute中使用它:

imageToShow: any;

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

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

如果您有多个图像,则可以将imageToShow [] = []定义为数组.现在你可以简单地将reader.result推送到这个数组.例如:this.imageToShow.push(reader.result).在模板中,您可以使用* ngFor =“let image of imageToShow;”迭代并输出此数组.

现在,您应该使用创建的ImageService从api获取图像.您应该订阅数据并将此数据提供给createImageFromBlob-function.这是一个示例函数:

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

现在,您可以在HTML模板中使用imageToShow变量,如下所示:

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

我希望这个描述清楚明白,你可以在你的项目中使用它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读