Coder949
Coder949

Reputation: 1007

Image preview with Angular

I have the following problem:

I want to make an image preview for uploaded images with <input type="file">. For that I need to get all images from the input which is no problem.

I came so far:

async handleFileInput(event: any) {

      this.filesToUpload = event.target.files;

        let test = await this.images(event);
        this.fileUrl = test;       
    }

    async images(event)
    {
        var reader = new FileReader();
        return new Promise<any>((resolve, reject) => {
            for (var i = 0; i < event.target.files.length; i++)
            {
               reader.onload = (event: any) => {
                    var data = event.target.result;
                    resolve(data);
                };
                reader.readAsDataURL(event.target.files[i]);
            }
        });
    }

But I can not find out how to get all images which were uploaded with Promise. With only one image everthing works fine. But how can I get all of them ?

When I enter more than one image I get the following error:

 Uncaught (in promise): InvalidStateError:
 An attempt was made to use an object that is not, or is no longer, usable

I know that I have to use an array if I want to resolve more than one image. I just wanted to show a working example. The problem is that I can only declare variables inside onload. So everything will be overwritten when the second image is uploaded.

The reason why I want to do that is that I can bind to the image urls like that:

<div *ngFor="let fileUrl of fileUrls">
    <img [src]="fileUrl">
</div>

Thank you for your help. I hope there is a working solution out there.

Upvotes: 4

Views: 564

Answers (1)

Stephen R. Smith
Stephen R. Smith

Reputation: 3400

I import DomSanitizer:

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

Add it to the constructor:

constructor(
     public sanitizer: DomSanitizer
){}

Then loop over the files array like this:

<div *ngFor="let fileUrl of fileUrls;let i=index">
      <img *ngIf="fileUrl[i]"[src]="sanitizer.bypassSecurityTrustUrl(fileUrl[i])">
 </div>

DomSanitizer ensures you're not open to cross-site scripting hacks, for example, someone passing a URL to a malicious JavaScript script to have code execute on your page.

Upvotes: 2

Related Questions