Check for file size with JavaScript before uploading

by Yang Yang on January 1, 2009

File uploading is a rather common feature of interactive sites. As all servers come with a limit on the size of the file being uploaded, it would be a usability blessing for users if web developers can implement a logic to check for the file size before uploading, informing the user if the size of the file exceeds the max allowed.

At the server side, it’s easy to weigh the file in bytes, with PHP, ASP or JSP. However it would be waste of resources if one can only check the size of the file that has already been uploaded because there’s no point to it if he is trying to inform the user if the file is too large.

So can this be done on the client side?

Internet Explorer

Yes, but partially and indecently. JavaScript is built with client safety in mind thus given no clearance to access client file system, falling unable to get the size of any chosen file. VBScript, on the other hand, can return the size of any client file with the help of ActiveX Object, the Microsoft proprietary scripting API.

Consider the code below:

function getSize()
	var myFSO = new ActiveXObject("Scripting.FileSystemObject");
	var filepath = document.upload.file.value;
	var thefile = myFSO.getFile(filepath);
	var size = thefile.size;
	alert(size + " bytes");
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">

Rather gross and obselete code with regard to modern front end coding standards, though it does the job. Run it on IE, select a file and click “Size?”, the browser alerts with the size of the file.

file size got by javascript

For IE, it’s the only way I know as of now that successfully checks the size of a given file completely on client side.

Firefox, Chrome, Opera, Safari, etc.

Now from hell to heaven, it’s much more doable than you may think. And it should be this way. For a file upload control like this:

<input type="file" id="myFile" />

With jQuery and the HTML5 File API specification implemented, you can use this simple snippet to access file properties such as size:

//binds to onchange event of your input field
$('#myFile').bind('change', function() {

Thanks to Felipe Sabino for this solution.