Rasmus Hansen
Rasmus Hansen

Reputation: 1573

Angular: Using selected file for image preview

As part of our application we would like to preview the files the users are uploading, before they are actually available on the server. To do this I have tried a couple of things:

And during none of these the background image actually appeared. I checked the dom using the chrome inspecter, and in none of the cases did the attribute actually get set.

So what is the correct way of doing this? I have a File instance at start.

Upvotes: 3

Views: 9003

Answers (1)

Joe Belladonna
Joe Belladonna

Reputation: 1339

HTML:

<input type='file' (change)="onAdd($event)">

<div class="col-4 col-sm-4 col-md-4 col-lg-4 col-xl-4" *ngIf="url">
    <img [src]="url">
</div>

Type Script:

onAdd(event: any) {
        console.log(event);
        if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();
            reader.onload = (event: any) => {
                this.slika = event.target.result;
            }
            reader.readAsDataURL(event.target.files[0]);
        }
    }

EDIT:

Change your code to this:

public addFile(event: any) {
    if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();
            reader.onload = (event: any) => {
                this.url = event.target.result;
            }
            reader.readAsDataURL(event.target.files[0]);
        }
  }

and this:

<input type="file" (change)="addFile($event)">

With these changes it should work now.

Upvotes: 11

Related Questions