0

I have the following Typescript function that when called opens a window to request a file, and after the user makes a selection it prints in the console the file contents.

The first time it works fine, but the problem is that if I call it twice, it doesn't work. The second time it opens the window, but when the file is selected it does nothing. What is wrong with this function?

<input id="file-input" type="file" name="name" style="display: none;" />


printFile(){

    var input = document.getElementById('file-input');

    input.addEventListener('input', () => {

        var uploadedFile = (input as HTMLInputElement).files[0];

        var reader = new FileReader();

        reader.addEventListener('load', () => {
            console.log(reader.result);
        });
          
        reader.readAsText(uploadedFile);

    });
          
    input.click();

}
ps0604
  • 1,227
  • 23
  • 133
  • 330

2 Answers2

2

You are adding a listener to FileReader and then instantiating it again. The correct way of working should look like (a similar sample but using images):

HTML

<input
  #fileInput
  type="file"
  accept="image/png, image/jpeg"
  (change)="handleChosenFile($event)"
/>

Typescript

handleChosenFile(event: Event) {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length) {
    this.selectedFile = target.files.item(0);
    const reader = new FileReader();
    reader.readAsDataURL(this.selectedFile);
    reader.onload = () => {
      // Your function
    };
  } else {
    // Your alert to "no file selected"
  }
}
Lucas Simões
  • 589
  • 5
  • 10
1
 reader.addEventListener('load', () => {
            console.log(reader.result);
        });

should be

 reader.addEventListener('load', (event) => {
            console.log(event.target.result);
        });
JB_DELR
  • 737
  • 1
  • 4
  • 7