用js控制上传照片的大小
<p>
<span> 上传照片: </span>
<input class= "input-3-1 " type= "file " name= "ephoto " onkeydown= "return false " oncontextmenu= "return false " onchange= "submitForm(); "/>
p>
目的是:上传照片的大小不能超过1M,且形象照格式只能是GIF、JPG、BMP、PNG四种格式,
需在客户端写个js来验证,改怎么写啊,谢谢大家,很急!!
------解决方案--------------------同意LS的,客户端容易被绕过,会增加服务器负担。
------解决方案-------------------- <script language= "javascript ">
var img=null;
function s()
{
if(img)img.removeNode(true);
img=document.createElement( "img ");
//img.style.position= "absolute ";
// img.style.visibility= "hidden ";
// img.attachEvent( "onreadystatechange ",orsc);
// img.attachEvent( "onerror ",oe);
// document.body.insertAdjacentElement( "beforeend ",img);
img.src=document.product.FilePath.value;
alert(img.fileSize)
}
function oe()
{
alert( "上传图片类型为:GIF、JPEG/JPG、BMP ");
}
function orsc()
{
if(img.readyState!= "complete ")return false;
else
alert(img.fileSize)
}
</script>
<body leftmargin= "0 " topmargin= "0 ">
<form name= "product ">
上传图片 <input type=file name= "FilePath " size=8 onpropertychange= "return s(); ">
</form>
------解决方案-------------------- <head>
<script>
var filesize=0;
function checkform(){
var str=document.form1.photo.value
var ext=str.substring(str.length-3,str.length).toLowerCase()
if(ext!= 'gif ' && ext!= 'jpg ' && ext!= 'bmp ' && ext!= 'png '){
alert( '必须是gif,jpg,bmp或png格式的图片! ')
document.form1.photo.focus();
return false;
}
upload_check();
}
var img=null;
function upload_check(){
if(img) img.removeNode(true);
img=document.createElement( "img ");//创建一个 <img...> 对象
img.style.position= "absolute ";//设置图片位置属性
img.style.visibility= "hidden ";//设置图片显示/隐藏属性
img.attachEvent( "onreadystatechange ",imgSize);//绑定函数到事件
img.attachEvent( "onerror ",err);
document.body.insertAdjacentElement( "beforeend ",img);//插入img对象到body
img.src=document.form1.photo.value;//设置图片src属性
}
function err(){//出错处理
alert( "cant load img ");
}
function imgSize(){
if(img.readyState!= "complete ")return false;
filesize=img.fileSize;//用obj.fileSize获取上传文件的大小
if(filesize> =(1024*1024)){//判断文件大小
alert( '图片文件必须小于1M,请重新选择! ');
document.form1.photo.focus();
return false;
}
document.form1.submit();
}
</script>
</head>
<body>
<form name= "form1 " action= " ">
照片: <input type= "file " name= "photo " value= " " onchange= "checkform(); ">
</form>
</body>