angular - 显示图像时出现不安全的 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 发出的警告,因为您的应用程序可能会受到 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 安全风险!
推荐阅读
- cors - dotnet core 3.1 中的 Cors 问题,带有选项请求
- node.js - 使用 express-validator 如何检查值?
- javascript - 修改所有 html 元素继承的类的构造函数以默认在它们上添加事件侦听器?
- azure - Azure Devops 模板中对象参数类型的使用
- sql - 使用滞后根据当前行值选择上一行
- node.js - 来自 mongoDB 的 nodejs 查询中的数据返回缓慢
- .net - 是否可以通过自定义操作从 CPQ 上的二进制代码填充 PDF 输出?
- reactjs - React Slick 点覆盖文本
- flutter - 如何在颤动中平稳地停止中间的动画?
- c# - 如何在 Xamarin.Forms.Maps 中自定义 MkMapView 标注/视图