Check Image Width, Height and its Type before Uploading using JavaScript

Whether you are working on an e-commerce site or a web application that requires uploading of images or files, then it is important to do some validations on the files before uploading. Here in this post, I’ll show how quickly and efficiently you can check the width, height and format of multiple images or files using plain JavaScript.

It is important to do some basic validations at the client side itself, before uploading the image or any file, to the server. This will ensure that the user is uploading the correct file type and size.

See this Demo

jQuery makes this simple. However, knowing how to do this using JavaScript is always good.

Along with the file (image) width, height and its format, I’ll show you how to check the file’s last modified date. Its useful in case it’s a Word or Excel file.

Also Read: FileReader API – Resize an Image on your Computer with FileReader and HTML5 Canvas without Losing Image Quality

The Markup

In my markup section, I have an input box of type file. Since I wish to check multiple files at a time, I’ll add the multiple attribute to the input type.

<body>
    <input type="file" id="file" multiple onchange="checkFileDetails()" />
    <p id="fileInfo"></p>
</body>

I’ll check the details of the file(s) as soon as I select it. Therefore, I am using the onchange event to call a function to check the file details.

The Script
<script>
function checkFileDetails() {
        var fi = document.getElementById('file');
        if (fi.files.length > 0) {      // FIRST CHECK IF ANY FILE IS SELECTED.
           
            for (var i = 0; i <= fi.files.length - 1; i++) {
                var fileName, fileExtension, fileSize, fileType, dateModified;

                // FILE NAME AND EXTENSION.
                fileName = fi.files.item(i).name;
                fileExtension = fileName.replace(/^.*\./, '');

                // CHECK IF ITS AN IMAGE FILE.
                // TO GET THE IMAGE WIDTH AND HEIGHT, WE'LL USE fileReader().
                if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
                   readImageFile(fi.files.item(i));             // GET IMAGE INFO USING fileReader().
                }
                else {
                    // IF THE FILE IS NOT AN IMAGE.
                        
                    fileSize = fi.files.item(i).size;  // FILE SIZE.
                    fileType = fi.files.item(i).type;  // FILE TYPE.
                    dateModified = fi.files.item(i).lastModifiedDate;  // FILE LAST MODIFIED.

                    document.getElementById('fileInfo').innerHTML =
                        document.getElementById('fileInfo').innerHTML + '<br /> ' +
                            'Name: <b>' + fileName + '</b> <br />' +
                            'File Extension: <b>' + fileExtension + '</b> <br />' +
                            'Size: <b>' + Math.round((fileSize / 1024)) + '</b> KB <br />' +
                            'Type: <b>' + fileType + '</b> <br />' +
                            'Last Modified: <b>' + dateModified + '</b> <br />';
                }
            }

            // GET THE IMAGE WIDTH AND HEIGHT USING fileReader() API.
            function readImageFile(file) {
                var reader = new FileReader(); // CREATE AN NEW INSTANCE.

                reader.onload = function (e) {
                    var img = new Image();      
                    img.src = e.target.result;

                    img.onload = function () {
                        var w = this.width;
                        var h = this.height;

                        document.getElementById('fileInfo').innerHTML =
                            document.getElementById('fileInfo').innerHTML + '<br /> ' +
                                'Name: <b>' + file.name + '</b> <br />' +
                                'File Extension: <b>' + fileExtension + '</b> <br />' +
                                'Size: <b>' + Math.round((file.size / 1024)) + '</b> KB <br />' +
                                'Width: <b>' + w + '</b> <br />' +
                                'Height: <b>' + h + '</b> <br />' +
                                'Type: <b>' + file.type + '</b> <br />' +
                                'Last Modified: <b>' + file.lastModifiedDate + '</b> <br />';
                    }
                };
                reader.readAsDataURL(file);
            }
        }
    }
</script>

See this Demo

First, I’ll create a file object and loop through each files in the object. To get the file extension, I am using the replace() method with Regular Expressions.

Also Read: 3 Simple Ways to Find the File Extension in JavaScript

The HTML DOM item() method provides some properties, using which you can get other details of the file(s). For example, add the below code inside the for loop.

console.log(fi.files.item(i));

The size property returns the file size in bytes. I am converting it into KB or Kilo Bytes by dividing it with 1024. Since 1 Kilo Byte equals 1024 bytes.

Math.round((fsize / 1024))

However, if its an image file, we'll have to use the fileReader API to get the width and height of image.

Well, that’s it. Thanks for reading.

Previous - SELECT Element Set Focus on Page Load or Expand SELECT Options on Page LoadNext - How to Auto Refresh Page Every 10 Second using JavaScript setInterval() Method



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!