How To Get File Size Using JavaScript

Server Resource more cost then client's. That's why validating forms in client is the best practice for every developer. We can validate form fields of type text,radio,check box,etc.. on client side very easily.  But for files validation not so easy. Today I will explain how to do client side file size validation.
File API All latest Versions browsers IE10, Chrome,FF,etc. support File API engine. By using this we can easily get file size on client side. Lets take an example. The following is your file input field.

<form name="fupload" action="">  
<input type="file" id="Fuploader" />  
</form> 

To find file size we will use the following JavaScript code.

var fSize = document.getElementById('Fuploader').files[0].size //size in kb 

This code work absolutely fine in IE10,chrome,FF. But in IE7,IE8,IE9. This code won't work because these browsers don't support file API.
We can use different fallback methods. For example we can use Flash up loader or Java script up loader. But it is based on assumption that   clients have installed these plug ins in there system.
Since we are facing Problem With IE another fallback technique is Using ActiveX object.  We are lucky that most of the machine will have this ActiveX object. So we can use ActiveX object to find file size.
ActiveX code

var AxFSObj = new ActiveXObject("Scripting.FileSystemObject");  
var filePath = $("#" + fileid)[0].value;  
var AxFSObjFile = AxFSObj.getFile(filePath);  
var fileSize = AxFSObjFile .size; //in kb 

Compleate Code

<!DOCTYPE html>  
<head>  
<title>How To Get File Size Using JavaScripte:Techumber</title>  
<script type="text/javascript">  
window.onload = function () {  
var sbt = document.getElementById("submit");  
sbt.onclick=function(){  
var Size = 0;  
var file=document.getElementById("file");  
if (navigator.appName.indexOf("Microsoft")) {  
var AxFSObj = new ActiveXObject("Scripting.FileSystemObject");  
var AxFSObjFile = AxFSObj.getFile(file);  
Size = AxFSObjFile.size; //in kb  
} 
else {  
Size = file.size;  
} 
alert("Your File Size is"+Size);  
} 
} 
</script>  
</head>  
<body>  
<form name="filesizefinnder" action="post">  
<input type="file" name="file" id="file" />  
<input type="button" value="Submit" id="submit" />  
</form>  
</body>  
</html> 

That's it! hope you like it

Get posts by email

Like what you're reading? Get these posts delivered to your inbox.