By the way, you can also do this using jQuery.
Along with image width, height and its format, I’ll show you how to check the file’s last modified date.
I have an input box of type "file". I want to check multiple files at a time, therefore I have added the multiple attribute to the input type.
<html> <body> <input type="file" id="file" multiple onchange="checkFileDetails()" accept="image/*" /> <p id="fileInfo"></p> <!--show images info here--> </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.
<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(/^.*\./, ''); // get image info using fileReader() readImageFile(fi.files.item(i)); } // GET THE IMAGE WIDTH AND HEIGHT USING fileReader() API. function readImageFile(file) { var reader = new FileReader(); // Create a 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> </html>
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.
The HTML DOM "item()" method provides properties, which helps to get other details of the file(s). For example, add the below code inside the for loop, and see what happens.
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.