Angular2 Base64清理不安全的URL值

时间:2017-03-31 13:08:34

标签: angular

我服务器的响应如下:

[{"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错误。这里出了什么问题?如果我从<img />删除管道,则表示不安全的网址。

2 个答案:

答案 0 :(得分:38)

你需要

bypassSecurityTrustResourceUrl(html);

而不是

bypassSecurityTrustHtml(html);

答案 1 :(得分:-1)

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