23

I have input file (without submit - typicall input file). I'd like to call some function when chose file.

Example: I click on "Choose file" -> choose file -> now system detects change and call some function which prints all these file information (for example image name).

I can't use ngModel on input file, right? How to do that?

3 Answers 3

57

Use the following in your template:

<div class="modal-body">
   <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
   <img id="preview" src="" alt="Preview">
</div>

Then your Component fileChangeEvent() as

public fileChangeEvent(fileInput: any){
      if (fileInput.target.files && fileInput.target.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e : any) {
            $('#preview').attr('src', e.target.result);
        }

        reader.readAsDataURL(fileInput.target.files[0]);
    }
}

All Your File related info will console....

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, it works. Have you any idea how could I be able to display selected photo? There is no path in fileInput.target.files response.
And what if i have to submit/upload the same file two times? the change event isn't fired if i choose the same file twice. Is there some sort of submit event i can use?
Is there a type we can use here instead of "any"? I've got any disabled in my project
@MartijnvandenBergh see Chris answer below.
7

Here's my amendments to Double H's answer to not rely on jQuery and stop the webpack erroring out on e.target.result.

<img [src]="imageSrc" alt="" />
<input type="file" capture="camera" accept="image/*" (change)="displayPhoto($event)">

Typescript Code

displayPhoto(fileInput) {
  if (fileInput.target.files && fileInput.target.files[0]) {
  const reader = new FileReader();

  reader.onload = ((e) => {
    this.imageSrc = e.target['result'];
  });

  reader.readAsDataURL(fileInput.target.files[0]);
}

}

Comments

5

Double H's function didn't work for me till I added onclick="this.value = null" as found here: https://stackoverflow.com/a/42357862/634650

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.