【问题标题】:Angular2 Base64 sanitizing unsafe URL valueAngular2 Base64 清理不安全的 URL 值
【发布时间】:2017-08-25 18:37:11
【问题描述】:

来自我的服务器的响应如下所示:

[{"coreGoalId":1,"title":"Core goal 1","infrastructure":"Sample Infrastructure","audience":"People","subGoals":null,"benefits":[{"benefitId":1,"what":"string","coreGoalId":1}],"effects":null,"steps":null,"images":[{"imagelId":1,"base64":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcU\nFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo\nKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wgARCAIWAe4DASIA\nAhEBAxEB/8QAHAABAAIDAQEB"}]}]

我正在尝试显示其中返回的 base64 图像。

在我的组件中:

ngOnInit() {

    this.homeService.getGoals()
    .subscribe(
        goals => this.coreGoals = goals,
        error =>  this.errorMessage = <any>error);
}

然后在模板中:

<ul>
    <li *ngFor="let goal of coreGoals">
        {{goal.title}}
        <img [src]="'data:image/jpg;base64,'+goal.images[0].base64 | safeHtml" />
    </li>
</ul> 

其中 safeHtml 是我创建的管道,如下所示:

import { Pipe } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'safeHtml'})
export class SafeHtml {
  constructor(private sanitizer:DomSanitizer){}

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

这给了我Required a safe URL, got a HTML 错误。这里出了什么问题?如果我从&lt;img /&gt; 中删除管道,那么它会显示不安全的 url。

【问题讨论】:

    标签: angular


    【解决方案1】:

    你需要

    bypassSecurityTrustResourceUrl(html);
    

    而不是

    bypassSecurityTrustHtml(html);
    

    【讨论】:

    • 谢谢!那是我的错误。
    • 我还建议您为您的管道启用pure:true
    【解决方案2】:

    我有同样的问题。我们的应用程序“X”用于存储本地上传的图像,方法是在将其保存到数据库之前将其转换为 base64(我们曾经弹出初始数据,即 data:image/jpg;base64)。在恢复它以显示时,我遇到了同样的问题。我曾经将弹出的数据连接到恢复的 base64 字符串。它曾经抛出上述错误。因此,我们决定存储整个转换后的字符串而不弹出它,现在它工作正常。看看,有没有帮助!

    【讨论】:

      猜你喜欢
      • 2021-05-10
      • 2018-11-09
      • 2016-11-30
      • 2018-06-05
      • 2016-11-28
      • 2017-05-08
      • 2019-06-18
      • 2018-06-05
      • 1970-01-01
      相关资源
      最近更新 更多