Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 and window.URL.createObjectURL

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.

like image 509
Bing Qiao Avatar asked Sep 27 '16 21:09

Bing Qiao


People also ask

What is window URL createObjectURL?

The URL. createObjectURL() static method creates a string containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.

Is createObjectURL Async URL?

createObjectURL is synchronous but it seems to complete almost instantaneously.

How to create Blob object in Angular?

To create a Blob we call new Blob() then call window. URL. createObjectURL() to convert it into a URL.


1 Answers

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"
like image 174
Pankaj Parkar Avatar answered Sep 20 '22 20:09

Pankaj Parkar