<input type="file" name="fileUpload" [(ngModel)]="fileUpload" (change)="sendImg($event)"/> sendImg(event) { let url = window.URL.createObjectURL(event.srcElement.files[0]); } // 获取到一个不安全的临时图片链接地址
2、在angular2中使用,定义管道,过滤
import { Pipe,PipeTransform,SecurityContext } from '@angular/core'; import { DomSanitizer,SafeHtml,SafeStyle,SafeScript,SafeUrl,SafeResourceUrl } from '@angular/platform-browser'; @Pipe({ name: 'safe' }) export class SafePipe implements PipeTransform { constructor(protected dom: DomSanitizer) {} public transform(value: string,type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl { switch (type) { case 'html': return this.dom.bypassSecurityTrustHtml(value); case 'style': return this.dom.bypassSecurityTrustStyle(value); case 'script': return this.dom.bypassSecurityTrustScript(value); case 'url': return this.dom.bypassSecurityTrustUrl(value); case 'resourceUrl': return this.dom.bypassSecurityTrustResourceUrl(value); default: return value; } } } 使用 <div [innerHTML]="html | safe:'html'"></div>