Check if file has changed using HTML5 File API

I don’t believe the File API has any event for the file changing, just progress events and the like.

Update August 2020: The alternative below no longer works, and the specification specifically disallows it by saying that the File object’s information must reflect the state of the underlying file as of when it was selected. From the spec:

User agents should endeavor to have a File object’s snapshot state set to the state of the underlying storage on disk at the time the reference is taken. If the file is modified on disk following the time a reference has been taken, the File’s snapshot state will differ from the state of the underlying storage.


You could use polling. Remember the lastModifiedDate of the File, and then when your polling function fires, get a new File instance for the input and see if the lastModifiedDate has changed.

This works for me on Chrome, for instance: Live Copy | Source

(function() {
  var input;
  var lastMod;

  document.getElementById('btnStart').onclick = function() {
    startWatching();
  };
    function startWatching() {
        var file;

        if (typeof window.FileReader !== 'function') {
            display("The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('filename');
        if (!input) {
            display("Um, couldn't find the filename element.");
        }
        else if (!input.files) {
            display("This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            display("Please select a file before clicking 'Show Size'");
        }
        else {
            file = input.files[0];
      lastMod = file.lastModifiedDate;
            display("Last modified date: " + lastMod);
      display("Change the file");
      setInterval(tick, 250);
        }
    }

  function tick() {
    var file = input.files && input.files[0];
    if (file && lastMod && file.lastModifiedDate.getTime() !== lastMod.getTime()) {
      lastMod = file.lastModifiedDate;
            display("File changed: " + lastMod);
    }
  }

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = msg;
    document.body.appendChild(p);
  }
})();
<input type="file" id='filename'>
<input type="button" id='btnStart' value="Start">

Leave a Comment