使用jQuery实现验证上传图片的格式与大小
代码很简单,常见的图片格式均已加入验证之中,小伙伴们可以直接拿去用的。
废话少说,直接上代码
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/> <scriptsrc="jquery-1.7.1.min.js"type="text/javascript"></script> <scripttype="text/javascript"> $(document).ready(function(){ $("#form01").change(function(){ varfilepath=$("input[name='myFile']").val(); varextStart=filepath.lastIndexOf("."); varext=filepath.substring(extStart,filepath.length).toUpperCase(); if(ext!=".BMP"&&ext!=".PNG"&&ext!=".GIF"&&ext!=".JPG"&&ext!=".JPEG"){ alert("图片限于bmp,png,gif,jpeg,jpg格式"); returnfalse; }else{$("#name01").text(ext)} varfile_size=0; if($.browser.msie){ varimg=newImage(); img.src=filepath; while(true){ if(img.fileSize>0){ if(img.fileSize>3*1024*1024){ alert("图片不大于100MB。"); }else{ varnum03=img.fileSize/1024; num04=num03.toFixed(2) $(".size02").text(num04+"KB"); } break; } } }else{ file_size=this.files[0].size; console.log(file_size/1024/1024+"MB"); varsize=file_size/1024; if(size>10240){ alert("上传的文件大小不能超过10M!"); }else{ varnum01=file_size/1024; num02=num01.toFixed(2) $("#size01").text(num02+"KB"); } } returntrue; }); }); </script> <title>无标题文档</title> </head> <body> <tablewidth="500"cellspacing="0"cellpadding="0"> <tr> <tdwidth="72"id="name01"> </td> <tdwidth="242"><inputtype="file"name="myFile"id="form01"/></td> <tdwidth="184"id="size01"class="size02"> </td> </tr> </table> </body> </html>
以上代码超级简单,小伙伴们使用的时候自己记得美化下,这里就不多做解释了。