angular2 http get image 显示到页面
我们的server端会返回一个image/* (image/jpeg,image/png等等) 的图片对象,我预先定义了在http请求的入参中返回值的类型为blob export interface RequestOptionsArgs { url?: string; method?: string | RequestMethod; search?: string | URLSearchParams; headers?: Headers; body?: any; withCredentials?: boolean; responseType?: ResponseContentType; } export declare enum ResponseContentType { Text = 0,Json = 1,ArrayBuffer = 2,Blob = 3,} 上图是angular的源代码,所以我的代码是根据blob来操作的 在typescript中需要将该对象解析,然后显示到页面上 页面部分: <img [src]="imageData | safeUrl"> 其中safeUrl是个过滤器,代码如下: import { Pipe,PipeTransform } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Pipe({ name: 'safeUrl' }) export class SafeUrlPipe implements PipeTransform { constructor(private domSanitizer: DomSanitizer) {} transform(url) { return this.domSanitizer.bypassSecurityTrustResourceUrl(url); } } 为什么要加这个过滤器呢?下面会讲到 typescript部分: getThumbnailImage(){ this.service.getThumbnailImage(this.id,(resp)=>{ let urlCreator = window.URL; this.imageData = urlCreator.createObjectURL(resp._body); console.log(this.imageData); }); } 这个函数的作用是通过id去获取server端的图片,resp是返回值,返回值中的_body就是图片对象,通过使用rulCreator的方法,可以得到一个blob:https的图片对象路径,但是这个blob路径在浏览器中会显示为unsafe,比如获取到的url为:blob:https://127.0.0.1/031c6651-7236-477f-99ae-44f775f9f17e,那么加在img标签src中的值为变为:unsafe:blob:https://127.0.0.1/031c6651-7236-477f-99ae-44f775f9f17e,这是angular的语法造成的,会自动为https等不安全链接加上前缀,这时候就需要使用angular的browser来去掉这个前缀,将去掉前缀的方法写成一个pipe这样简洁明了,使用方便 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |