在 Angular 6 中显示图像时在控制台中出现不安全的 URL 错误
我在这里拍照
<br>Primary Image <input type="file" (change)="readUrl($event)">
Run Code Online (Sandbox Code Playgroud)
在另一个组件中,我希望显示我的图像
<tr *ngFor="let x of response">
<td>
<img [src]="x.productPrimaryImage">
</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
获取图片路径的方法。
readUrl(event) {
this.productPrimaryImage = event.target.value;
}
Run Code Online (Sandbox Code Playgroud)
警告:清理不安全的 URL 值 C:\Users\mayursinghal\Pictures\Screenshot (9).png(参见http://g.co/ng/security#xss)
这是 Angular 发出的警告,因为您的应用程序可能会受到 XSS 攻击。如果您想绕过此安全警告,您需要首先清理 URL 以使其安全地显示在 UI 中。您可以使用DomSanitizer
(来源:docs)来做到这一点。
创建一个函数来清理组件中的图像 url
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
...
constructor(private sanitizer: DomSanitizer) { }
sanitizeImageUrl(imageUrl: string): SafeUrl {
return this.sanitizer.bypassSecurityTrustUrl(imageUrl);
}
Run Code Online (Sandbox Code Playgroud)
然后在您的模板中,调用此函数来清理您的 URL。
<tr *ngFor="let x of response">
<td>
<img [src]="sanitizeImageUrl(x.productPrimaryImage)" />
</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
警告:
bypassSecurityTrustUrl
使用不受信任的图像 URL调用会使您的应用程序暴露于 XSS 安全风险!
归档时间: |
|
查看次数: |
4048 次 |
最近记录: |