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?
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)">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With