Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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?

like image 790
Dan Avatar asked Oct 21 '25 03:10

Dan


1 Answers

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)">
like image 165
AArias Avatar answered Oct 23 '25 18:10

AArias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!