2016-09-16 96 views
5

我想呈现base64字符串到<img src='data:image/png;base64,${Here}'Angular 2禁用清理

但总是当我尝试呈现它时,ng2在渲染之前清理我的base64字符串,然后在DOM中显示它之前将值添加到我的值中。 我找到了解决方法(使用DomSanitizer),但它不适用于最新版本。

这里是我的标记:

<img alt="RegularImage" src="data:image/png;base64,{{imgBase64}}"> 

这里是我的组成部分:

imgBase64="SomeBase64StringFetchedSomehow"; 

但angular2在控制台中显示一条消息 - WARNING: sanitizing unsafe URL value

如何防止NG2从消毒我的base64字符串?

更新

get getImg() { 
    return this._sanitizer.sanitize(SecurityContext.URL,`data:image/png;base64,${this.img}`); 
} 

并不能解决这个问题。 DomSanitizer类不RC6不再存在

+1

你为什么不使用最终代替RC.6的? –

+0

刚刚尝试了RC.7并发布了angular2版本。 – Maris

回答

3

几个小时后我最终发现,在最新版本的ng2中是否可以使用DI注入DomSanitizer,但有Sanitizer。因此,这里的用法:

constructor(private _sanitizer: Sanitizer){ 
} 

get getImg() { 
    return this._sanitizer.sanitize(SecurityContext.URL, `data:image/png;base64,${this.img}`); 
} 

<input src="{{getImg}}"/> 

正如你可以看到sanitize方法的第一个参数是SecurityContext情况下,这基本上是枚举。所以现在Sanitizer是一个工厂,选择实施使用基于SecurityContext

在我来说,我必须在此之前得到的,那为什么我无法得到它的工作,我的base64被消毒的问题。

5

你需要明确地告诉Angular2该字符串被信任

https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html

constructor(private sanitizer:DomSanitizer) {} 

get imgBase64() { 
    this.sanitizer.bypassSecurityTrustUrl('data:image/png;base64,$SomeBase64StringFetchedSomehow'); 
} 
<img alt="RegularImage" [src]="imgBase64"> 

参见In RC.1 some styles can't be added using binding syntax

+0

不再有DomSanitizer类。我正在尝试使用新的 - “Sanitizer”,但它失败的同样的错误。 '返回this._sanitizer.sanitize(SecurityContext.URL,'data:image/png; base64,$ {this.img}');' – Maris

+0

当然有。检查我的答案中的链接(导入信息位于网站的底部)。 (以前它被命名为'DomSanitizationService') –

+0

模块'“.../node_modules/@ angular/core/index”'没有导出成员'DomSanitizer' – Maris

0

未果后试图让bypassSecurityTrust ...职能工作,我使出了以下内容:

@ViewChild('div_element_id') private div_element_id: ElementRef; 
... 

this.div_element_id.nativeElement.innerHTML = bypass_security_for_this_html; 
+0

哦,我的。不,这不应该完成。绕过卫生条件让你面对XSS攻击。 – TimTheEnchanter