Why is Javascript's `file.lastModified` not returning the original modification date but rather the upload date for uploaded files?

Viewed 146

I am trying to access the last modification of files that are uploaded using http post. I thought this would be possible by setting an event listener on the upload button and saving the lastModified field like this:

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var modification_dates = [];
    var file_sizes = [];
    var file_types = [];
    var file_names = [];
    for (var i = 0, f; f = files[i]; i++) {
      modification_dates.push(f.lastModified);
      file_sizes.push(f.size);
      file_types.push(f.type);
      file_names.push(f.name);
    }
    // Pass data to Django
    alert(Date(modification_dates[0]))
  }

  // Check for the various File API support.
  if (window.File && window.FileReader && window.FileList && window.Blob) {
    // Great success! All the File APIs are supported.
  } else {
    alert('The File APIs are not fully supported in this browser.');
  }

  document.getElementById('id_file').addEventListener('change', handleFileSelect, false);

However if I upload a file that was last modified on the 15th of January 2019 the alert does not show this date but rather today's date:

Alert window displays today's date instead of original modification date.

How can I get the last modification date of the original file instead of the upload date?

1 Answers

It seems you are simply missing the new operator before Date(modification_dates[0]).

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var modification_dates = [];
    var file_sizes = [];
    var file_types = [];
    var file_names = [];
    for (var i = 0, f; f = files[i]; i++) {
      modification_dates.push(f.lastModified);
      file_sizes.push(f.size);
      file_types.push(f.type);
      file_names.push(f.name);
    }
    // Pass data to Django
    alert(new Date(modification_dates[0]))
  }

  // Check for the various File API support.
  if (window.File && window.FileReader && window.FileList && window.Blob) {
    // Great success! All the File APIs are supported.
  } else {
    alert('The File APIs are not fully supported in this browser.');
  }

  document.getElementById('id_file').addEventListener('change', handleFileSelect, false);
<input type="file" id="id_file" />

Hope this helps.

Related