angular2 and window.URL.createObjectURL

て烟熏妆下的殇ゞ 提交于 2019-12-01 18:09:22

问题


I use window.URL.createObjectURL to create a blob:http link for previewing selected image in an img tag:

<img src=""{{itemPhoto}}"" />

itemPhoto is a field defined in a component and gets assigned when an image file is selected:

selectPhoto(photos: any[]) {
    if (photos[0]) {
      this.itemPhoto = window.URL.createObjectURL(photos[0]);
    }
  }

This works in angular2 RC1 but no longer works in 2.0.0.

Here is what gets into the src attribute:

unsafe:blob:http://localhost:5555/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxx

I tried the following after reading some other posts:

this.itemPhoto = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(photos[0]));

Then the following gets into the src attribute:

unsafe:SafeValue must use [property]=binding: blob:http://localhost:5555/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxx (see http://g.co/ng/security#xss)

Any suggestions?

Many thanks

Update: OK, I didn't really understand that error message inside src: "unsafe:SafeValue must use [property]=binding:..."

Instead of src={{itemPhoto}}, the following works:

<img [src]="itemPhoto" />

Still not sure why though.


回答1:


You could just try what error is trying to say. what it said is you have to use property [] binding instead of interpolation {{}} with attribute.

[src]="itemPhoto"


来源:https://stackoverflow.com/questions/39734409/angular2-and-window-url-createobjecturl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!