How to get the name, size, and type of a file in JavaScript
Before sending the file to the server for upload, it is always important to validate the file, using JavaScript, you can easily get information about the file and validate it on the client-side. The following line of code will help you get the file name, size, type, and modification date.
Get the file name in JavaScript:
document.getElementById('myFile').files[0].name
Get file size in JavaScript:
document.getElementById('myFile').files[0].size
Get the file type in JavaScript:
document.getElementById('myFile').files[0].type
Get the last modified date of a file in JavaScript:
document.getElementById('myFile').files[0].lastModifiedDate
Complete Example:
You can use the following code to get the file name, size, and type after selecting a file.
HTML Code:
<input type="file" id="myFile" onchange="getFileInfo()"/>
JavaScript Code:
function getFileInfo(){ var name = document.getElementById('myFile').files[0].name; var size = document.getElementById('myFile').files[0].size; var type = document.getElementById('myFile').files[0].type; var date = document.getElementById('myFile').files[0].lastModifiedDate; var info = name+" "+size+" "+type+" "+date; alert(info); }