Skip to content

Instantly share code, notes, and snippets.

@eagleon
Created June 5, 2012 14:35
Show Gist options
  • Save eagleon/2875382 to your computer and use it in GitHub Desktop.
Save eagleon/2875382 to your computer and use it in GitHub Desktop.
JavaScript获取文件的大小和类型
//<INPUT TYPE="file" NAME="file" onchange="getFileSizeAndType(this)"/>
function getFileSizeAndType(obj){
var maxSize= 1024 * 1024 *2;
var objValue = obj.value;
if (objValue=="") return false;
var pos = objValue.lastIndexOf(".");
var lastname = objValue.substring(pos,objValue.length);
if (lastname.toLowerCase()!=".jpg" && lastname.toLowerCase()!=".gif" && lastname.toLowerCase()!=".png" && lastname.toLowerCase()!=".jpeg")
{
alert("您上传的文件类型为"+lastname+",图片必须为.jpg,.gif,.png,.jpeg类型");
return false;
}
var fileLenth=-1;
try {
//对于IE判断要上传的文件的大小
var fso = new ActiveXObject("Scripting.FileSystemObject");
fileLenth=parseInt(fso.getFile(objValue).size);
} catch (e){
try{
//对于非IE获得要上传文件的大小
fileLenth=parseInt(obj.files[0].size);
}catch (e) {
fileLenth=-1;
}
}
if(fileLenth > maxSize)
{
alert("你上传的图片太大了,请上传2M以内的图片");
return false;
}
if(-1 == fileLenth)
{
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment