How to get the modified time of a file being uploaded in JavaScript?

If you’re talking about the file date/time on the user’s machine, you can get that via the File API (support), which provides lastModified, which is the date/time as a number of milliseconds since The Epoch (if you want a Date, you can pass that into new Date). (There’s also the deprecated lastModifiedDate, but that is deprecated and not supported on Safari [at least].) The File API is universally supported in modern browsers (the particular feature you’d be using is the File object). You’d get the value from the File object and include that information in a separate (for instance, hidden) field.

Here’s a rough-but-complete example of reading the last modified date (live copy):

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Modified</title>
<style type="text/css">
body {
    font-family: sans-serif;
}
</style>
<script type="text/javascript">

    function showFileModified() {
        var input, file;

        // Testing for 'function' is more specific and correct, but doesn't work with Safari 6.x
        if (typeof window.FileReader !== 'function' &&
            typeof window.FileReader !== 'object') {
            write("The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('filename');
        if (!input) {
            write("Um, couldn't find the filename element.");
        }
        else if (!input.files) {
            write("This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            write("Please select a file before clicking 'Show Modified'");
        }
        else {
            file = input.files[0];
            write("The last modified date of file '" + file.name + "' is " + new Date(file.lastModified));
        }

        function write(msg) {
            var p = document.createElement('p');
            p.innerHTML = msg;
            document.body.appendChild(p);
        }
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type="file" id='filename'>
<input type="button" id='btnShowModified' value="Show Modified" onclick='showFileModified();'>
</form>
</body>
</html>

The reason you couldn’t get the time from the uploaded file on the server is that only the content of the file is transmitted in the request, not the client’s filesystem metadata.

Leave a Comment