slipperypete
slipperypete

Reputation: 6246

How to display an image immediately after selecting it with ng2-file-upload?

I am building a site with angular2 and using the ng2-file-upload library ng2-file-upload I want to display an image on my site right after selecting it. How is this possible with this library?

Upvotes: 4

Views: 4449

Answers (2)

Sahil Ralkar
Sahil Ralkar

Reputation: 2424

follow the following simple solution

import { DomSanitizer} from '@angular/platform-browser';
    ...
    public previewPath: any;
    ....
    constructor(private sanitizer: DomSanitizer) {
       this.uploader.onAfterAddingFile = (fileItem) => {
          this.previewPath = this.sanitizer.bypassSecurityTrustUrl((window.URL.createObjectURL(fileItem._file)));
        }
    }

In html

 <img [src]="previewPath " alt="Avatar" class="contribution-image">

Upvotes: 3

AArias
AArias

Reputation: 2568

You can listen for onAfterAddingFile event and create the url for the local blob:

this.uploader = new FileUploader({url: '/your/url' });
this.uploader.onAfterAddingFile = (fileItem) => {
    let url = (window.URL) ? window.URL.createObjectURL(fileItem._file) : (window as any).webkitURL.createObjectURL(fileItem._file);
    this.localImageUrl = url
}

Now the img src you have to use is stored in this.localImageUrl. The problem is that when you try to use that in the DOM, Angular will mark it as unsafe. To overcome that, you need to import DomSanitizer:

import { DomSanitizer } from '@angular/platform-browser';

And inject it into your component's constructor:

export class MyComponent {
    (...)
    constructor(public sanitizer:DomSanitizer) {
    (...)
    }

Finally, where you add the img in your template, use the sanitizer to trust the url:

<img [src]="sanitizer.bypassSecurityTrustUrl(localImageUrl)">

Upvotes: 5

Related Questions