1

I'm trying to understand file I/O in Javascript and this is puzzling me. I have a file input which loads a file from disk then I use a reader to grab the contents. But when I repeat the process, the file will not read a second time or third time. This is the code:

<html>

<head>
</head>

<body>
  <input type="file" id="myFile">

  <script type="text/javascript">
    window.onload = function() {

      var input = document.getElementById("myFile");

      var output = document.getElementById("output");

      input.addEventListener("change", function() {

        if (this.files && this.files[0]) {

          var myFile = this.files[0];

          var reader = new FileReader();

          reader.addEventListener('load', function(e) {
            console.log(e.target.result);
          });

          reader.readAsText(myFile);

        }
      });
    }
  </script>
</body>


</html>

When I read the file the first time, console.log prints e.target.result. When I try reading the file a second time, it will not print. Even if I change the contents of the file. But it will print a new file I load into it. Is it possible to load the same file twice?

Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
Irelia
  • 3,407
  • 2
  • 10
  • 31
  • Try to change event type from "change" to "input". What you have works in Firefox btw. What browser are you using? –  Sep 04 '18 at 16:32
  • Thank you for the suggestion! I did get it to work with the answer below, but I am using chrome. Every example I saw used change so I wasn't sure what that callback really even did. I assume it checks for name change? But I'll change it to input as well. I think it's more convenient. – Irelia Sep 04 '18 at 17:30
  • Yeah, it's suppose to compare what you have already with what you select, and if different then trigger the event. The newer (i.e. not supported in IE) "input" event however will (or should) trigger on any selection. –  Sep 06 '18 at 02:01

1 Answers1

3

What happens is that the change event is not fired for the input if you are selecting the same file. ( the comparison is on the selected file name i think, nothing fancy like size or anything 'smart')

You can try clearing the selection just before the file browser opens, so even selecting the same file will result in a 'new' selection

MKougiouris
  • 2,821
  • 1
  • 16
  • 19
  • How would I be able to clear the selection? I have tried this but it doesn't seem to work: if(file.value){ file.value=''; } – Irelia Sep 04 '18 at 14:04
  • just setting the value to '' or undefined should work.. are you sure it is not working proeprly? – MKougiouris Sep 04 '18 at 14:14
  • Ah, I was doing it wrong. I added an id to the tag, then I use document.getelementbyid.value = ""; and that did the trick. Thank you! – Irelia Sep 04 '18 at 14:39