angular2 and window.URL.createObjectURL
Asked Answered
A

1

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.

Archon answered 27/9, 2016 at 21:14 Comment(8)
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: #37046633Slush
Just try what error is suggesting [src]="itemPhoto"Iceskate
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: <img [src]="itemPhoto" /> Still not sure why though.Archon
Thanks @PankajParkar that's exactly what I just tried and it works. Thanks!Archon
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.Slush
@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.Iceskate
@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?Slush
@StefanSvrkota you can go through doc reference if you want to moreIceskate
I
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"
Iceskate answered 27/9, 2016 at 21:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.