angular2 and window.URL.createObjectURL

2019-02-23 13:23发布

问题:

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"