0

I have the following situation:

<input type="file" name="profilePicture" id="profilePicture" accept="image/*" (change)="onFileSelected($event)" style="display:none"/>
<img *ngIf="!this.profile.profilePic" src="...a static path..." />
<img *ngIf="this.profile.profilePic" [src]="this.profile.profilePic" />

and I would like to trigger the input file on one of the two images that are displayed in the img tags, according with the ngIf. This means that I want the upload window to open when I click on the image without having the standard input of type "file" as usual. My code, as I wrote it here, doesn't work. Can anybody explain me how to trigger the upload file from the image tag and hide the input tag instead?

EDIT

The onFileSelected is only a function that processes the uploaded image and store the object in a temporary variable called profilePicture:

onFileSelected(event) {
  if (event.target.files.length > 0) {
     this.profilePicture = event.target.files[0];
   } else {
    this.profilePicture = undefined;
  }
}

profile is instead an object which contains all the info related to the user.

EDIT II

I tested the code by using only one img tag. The following code doesn't work either:

<input type="file" accept="image/*" (change)="onFileSelected($event)" style="display:none"/>
<img [src]="'...the static path...'"/> 

EDIT III

My problem is related to this question that address the same problem I have (and didn't help unfortunately).

Rexam
  • 823
  • 4
  • 23
  • 42

1 Answers1

1

Use FileReader class to read the content of file. The fileReader.result is only available when operation is complete.

Add the following to your TS:

imageSource;

onFileSelected(e: Event): void {
  if (e.target.files && e.target.files[0]) {
    const imageFile = e.target.files[0];

    const fileReader = new FileReader();
    fileReader.onload = () => {
      return this.imageSource = fileReader.result;
    };

    fileReader.readAsDataURL(imageFile);
  }
}

And bind the imageSource to your img tags:

<img [src]="imageSource || 'static path'" alt="My Profile Image"/>

You only need to add one img tag and works for both cases, if image available or pick it from the path defined.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
  • The problem is not to read the content of the file. The problem is to trigger the upload by clicking on the image that is currently displayed. I'm testing the code with only one img tag as you suggested. – Rexam Jun 11 '19 at 15:01
  • No, I want the upload window to open when I click on the image. If I use a separate input field with type="file" everything works perfectly, but I want the input window that allows you to pick up a file to open when I click on the image in the HTML. – Rexam Jun 11 '19 at 15:03