首页 > 解决方案 > 显示图像时出现不安全的 URL 错误

问题描述

在 Angular 6 中显示图像时在控制台中出现不安全的 URL 错误

我在这里拍照

<br>Primary Image <input type="file" (change)="readUrl($event)">

在另一个组件中,我希望显示我的图像

<tr *ngFor="let x of response">
    <td>
        <img [src]="x.productPrimaryImage">
    </td>
</tr>

获取图像路径的方法。

readUrl(event) {
    this.productPrimaryImage = event.target.value;
}

警告:清理不安全的 URL 值 C:\Users\mayursinghal\Pictures\Screenshot (9).png(参见http://g.co/ng/security#xss

标签: angular

解决方案


这是 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);
}

然后在您的模板中,调用此函数来清理您的 URL。

<tr *ngFor="let x of response">
    <td>
        <img [src]="sanitizeImageUrl(x.productPrimaryImage)" />
    </td>
</tr>

警告:bypassSecurityTrustUrl使用不受信任的图像 URL 调用会使您的应用程序面临 XSS 安全风险!


推荐阅读