这是出于安全考虑。 svg 和jpg/png 之间的区别在于结构,因为svg 使用xml 而jpg/png 是位图。所以当它们被翻译成base64时,svg是不可信的,jpg/png是可信的。
正如Angular documentation 所说
例如,当将 URL 绑定到
超链接,someValue 将被清理,以便攻击者无法
注入例如一个 javascript: 将在网站上执行代码的 URL。
更简单的方法
您可以将bypassSecurityTrustUrl() 添加到您的方法中
所以它看起来像这样
selectedImageChanged(event) {
const fileReader = new FileReader();
fileReader.onload = async e => {
const value = this.sanitizer.bypassSecurityTrustUrl(fileReader.result as string);
this.previewFileUrl = value;
}
fileReader.readAsDataURL(event.target.files[0]);
}
更复杂的方式
第二种可能的方法是创建一个管道来做同样的事情。
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
default: throw new Error(`Invalid safe type specified: ${type}`);
}
}
}
在您的代码中使用此管道非常简单,看起来像这样。
<img [src]="previewFileUrl | safe: 'url'" alt=alt/>
Stackblitz demo
不要忘记将 SafePipe 放入模块依赖项中。