0

This is in profile.component.html

<label for="profile">Profile Photo</label>
<input type="file" [(ngModel)]='input'/>
<img [src]='input'>

This is in profile.component.ts

profilePhoto: File;

set input(temp: File) {
    this.profilePhoto = temp;
 }

get input() {
    return this.profilePhoto;
}

1 Answers1

3

Firstly the [(ngModel)] on the File Input is actually providing a string, not a File object in here; set input(temp: File) { .. }.

Since some browsers protect the file path, this string path is often virtual (i.e. C:\fakepath\image.png). There are some work arounds but these are inconsistent across browsers. See more about this here; How to resolve the C:\fakepath?

Some browsers have a security feature that prevents JavaScript from knowing your file's local full path. It makes sense - as a client, you don't want the server to know your local machine's filesystem. It would be nice if all browsers did this.

In your case, you can simply use a FileReader to load the image data for your Image element. This is a similar process to what you might use if you want to later upload the file data too.

const fReader = new FileReader();
fReader.readAsDataURL(this.profilePhoto);
fReader.onloadend = (event) => {
  this.profilePhotoImage = event.target.result;
}

Working example here; https://stackblitz.com/edit/angular-cfvlhn

Ralpharoo
  • 789
  • 9
  • 21