Check Image Size before uploading in Javascript
by Mohan[ Edit ] 2014-04-03 13:14:25
<html>
<body>
<form action="" method="post" enctype="multipart/form-data" onsubmit="return validation(this)">
<input type="file" name="file"/>
<input type="submit" value="Upload"/>
<div id="valid_msg"/>
</form>
</body>
</html>
<script type="text/javascript">
function validation(thisform)
{
with(thisform)
{
if(validateFileExtension(file, "valid_msg", "image files are only allowed!",
new Array("jpg","pdf","jpeg","gif","png")) == false)
{
return false;
}
if(validateFileSize(file,1048576, "valid_msg", "Image size should be less than 1MB !")==false)
{
return false;
}
}
}
function validateFileExtension(component,msg_id,msg,extns)
{
var flag=0;
with(component)
{
var ext=value.substring(value.lastIndexOf('.')+1);
for(i=0;i<extns.length;i++)
{
if(ext==extns[i])
{
flag=0;
break;
}
else
{
flag=1;
}
}
if(flag!=0)
{
document.getElementById(msg_id).innerHTML=msg;
component.value="";
component.style.backgroundColor="#eab1b1";
component.style.border="thin solid #000000";
component.focus();
return false;
}
else
{
return true;
}
}
}
function validateFileSize(component,maxSize,msg_id,msg)
{
if(navigator.appName=="Microsoft Internet Explorer")
{
if(component.value)
{
var oas=new ActiveXObject("Scripting.FileSystemObject");
var e=oas.getFile(component.value);
var size=e.size;
}
}
else
{
if(component.files[0]!=undefined)
{
size = component.files[0].size;
}
}
if(size!=undefined && size>maxSize)
{
document.getElementById(msg_id).innerHTML=msg;
component.value="";
component.style.backgroundColor="#eab1b1";
component.style.border="thin solid #000000";
component.focus();
return false;
}
else
{
return true;
}
}
</script>
On uploading javascript checks for image size. If image size greater than 1 MB it will return error message.
like this
if uploaded file is not an image