我尝试使用 fileReader 和创建数据 url 使用 angular 进行图像预览,但图像从不加载 svg,但 jpg 等有效。
例子:stackblitz
我也尝试将其作为纯文本并将其作为innerHtml添加到有效的div中,但图像具有宽度:100mm和高度:100mm,这意味着图像不会缩放到其容器。我试图在 css 中改变它,但它也不起作用......
例子:stackblitz
我还添加了一些 svg img 到 src DIR 进行测试。
发生这种情况是因为安全。svg和之间的区别在于jpg/png结构,因为svg使用xml和jpg/png是位图。因此,当它们被翻译成base64 svg不可信且jpg/png可信时。
正如Angular 文档所说
例如,当在超链接中绑定 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]);
}
Run Code Online (Sandbox Code Playgroud)
第二种可能的方法是创建一个执行相同操作的管道。
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}`);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在您的代码中使用此管道非常简单,它看起来像这样。
<img [src]="previewFileUrl | safe: 'url'" alt=alt/>
Run Code Online (Sandbox Code Playgroud)
不要忘记将 SafePipe 放入模块依赖项中。
| 归档时间: |
|
| 查看次数: |
1440 次 |
| 最近记录: |