How can I validate the file size on the client side using JavaScript? I am using type=file
for selecting the file
UPDATE 2013 as of this edit, the File API is supported in all major browsers, and in IE as of version 10
http://caniuse.com/#search=file%20api
You may still wish to use SWFUpload if you still need to support IE9 and under, though at this point it should probably be more of a fallback, since the html5 file api has support on mobile platforms where SWFUpload cannot reach. The html5 file api is based on firefox's file api as noted below.
See also this duplicate question Client Checking file size using HTML5?
UPDATE: Firefox has changed their API to this https://developer.mozilla.org/en/DOM/FileReader
You can do it in firefox like so
html:
<form action="" method="get" accept-charset="utf-8"> <input type="file" name="file" value="" id="file"> <p><input type="submit" value="Continue →"></p> </form>
javascript:
var filesize = document.forms[0].file.files[0].fileSize
if there's a way to do this in IE, I don't know it. It probably involves activeX or some other such rubbish.
edit: I found this here, HOW TO DO THIS IN IE
<head>
<script>
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");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>
Perhaps you could use SWFUpload instead, which is a small Flash application that handles the client side of the upload for you. From their feature list:
I would like to combine the two different ways of checking file size on client side using javascript. I have tested it on FF/IE/Chrome and it works fine:
<script type="text/javascript">
function checkBrowser()
{
if(navigator.appName == "WebTV")
{
alert("You're using the WebTV browser.")
}
if(navigator.appName == "Netscape")
{
checkFileSizeFF();
}
if(navigator.appName == "Microsoft Internet Explorer")
{
checkFileSizeIE();
}
}
function checkFileSizeFF()
{
var filesize = document.forms[0].file.files[0].fileSize;
alert(filesize/(1024*1024) + " MB");
}
function checkFileSizeIE()
{
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size/(1024*1024);
alert(size + "MB");
}
</script>
<form action="" method="get" accept-charset="utf-8" name="upload">
<input type="file" name="file" value="" id="file">
<p><input type="submit" value="Continue →" onclick="checkBrowser()"></p>
</form>
<div id="example"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With