5

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.

Bing Qiao
  • 451
  • 1
  • 5
  • 14
  • I don't have time to take a closer look at your problem, but I had a similar problem a few days ago - I displayed a pdf using blob:http link, take a look at how I managed to do it here, it might help you: http://stackoverflow.com/questions/37046133/pdf-blob-is-not-showing-content-angular-2/39657478#39657478 – Stefan Svrkota Sep 27 '16 at 21:18
  • 1
    Just try what error is suggesting `[src]="itemPhoto"` – Pankaj Parkar Sep 27 '16 at 21:20
  • Hi Stefan I just found out what the problem is. I didn't really understand that error message inside src: "unsafe:SafeValue must use [property]=binding:..." Instead of src={{itemPhoto}}, the following works: Still not sure why though. – Bing Qiao Sep 27 '16 at 21:28
  • Thanks @PankajParkar that's exactly what I just tried and it works. Thanks! – Bing Qiao Sep 27 '16 at 21:34
  • Great, so suggestion by @PankajParkar worked. I'm not sure why you have to use sanitizer, I managed to open my pdf the exact same way (as you can see) without using it. – Stefan Svrkota Sep 27 '16 at 21:35
  • 1
    @StefanSvrkota sanitizer is needed to just say that I'm going to take image from another domain, for that you have to bypassing the security. – Pankaj Parkar Sep 27 '16 at 21:38
  • @PankajParkar Okay, that makes sense, but I can't find any proof that he's getting image from another domain. Am I missing something obvious? – Stefan Svrkota Sep 27 '16 at 21:40
  • @StefanSvrkota you can go through [doc reference](https://angular.io/docs/ts/latest/guide/security.html#!#bypass-security-apis) if you want to more – Pankaj Parkar Sep 27 '16 at 21:43

1 Answers1

5

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"
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299