g Get the Name, Size and Number of Files from Multiple File Input using JavaScript

Get the Name, Size and Number of Files from Multiple File Input using JavaScript

← PrevNext →

Using HTML5 file input element, you can upload multiple files at a time. All you have to do is add the multiple attribute of the <input> element. Having added this element to our web page, we often come across a situation where we want to get the total number of selected files, along with the name and size of each files. I’ll show you how to get the file details using JavaScript.

Show Selected File Details using JavaScript

Browser Support:
Chrome 39.0 - Yes | FireFox 34.0 - Yes | Internet Explorer 10 - Yes | Safari - No

Also Read: How can I get the X character in a String using JavaScript?

The Markup with the Script
<!DOCTYPE html>
<html>
<head>
    <title>Get File Details</title>
</head>
<body style="font:15px Calibri;">
    <!--ADD INPUT OF TYPE FILE WITH THE MULTIPLE OPTION-->
    <p>
        <input type="file" id="file" multiple />
    </p>
    
    <!--SHOW RESULT HERE-->
    <p id="fp"></p>

    <p>
        <input type="submit" value="Show Details" 
            onclick="FileDetails()" >
    </p>
</body>

<script>
    function FileDetails() {

        // GET THE FILE INPUT.
        var fi = document.getElementById('file');

        // VALIDATE OR CHECK IF ANY FILE IS SELECTED.
        if (fi.files.length > 0) {

            // THE TOTAL FILE COUNT.
            document.getElementById('fp').innerHTML =
                'Total Files: <b>' + fi.files.length + '</b></br >';

            // RUN A LOOP TO CHECK EACH SELECTED FILE.
            for (var i = 0; i <= fi.files.length - 1; i++) {

                var fname = fi.files.item(i).name;      // THE NAME OF THE FILE.
                var fsize = fi.files.item(i).size;      // THE SIZE OF THE FILE.

                // SHOW THE EXTRACTED DETAILS OF THE FILE.
                document.getElementById('fp').innerHTML =
                    document.getElementById('fp').innerHTML + '<br /> ' +
                        fname + ' (<b>' + fsize + '</b> bytes)';
            }
        }
        else { 
            alert('Please select a file.') 
        }
    }
</script>
</html>
Try it

Using document.getElementById('file'), I am first getting a reference of the input element. The fi.files property has a list of files in the form of an array and therefore I am checking the length (total selected files), to ensure if the user has selected any file. Once confirmed, now you can loop through each file and get the name and size of the file.

Browser Support:
Chrome 39.0 - Yes | FireFox 34.0 - Yes | Internet Explorer 10 - Yes | Safari - No

Also Read: Two simple methods to get the File size before uploading using JavaScript and jQuery

Note: Safari seems to have a bug. It cannot get the size of multiple files (inside the loop). However, it will get the size of a single selected file.
Well, that’s it.

← PreviousNext →