提交图片校检
目的:在提交表单之前用JavaScript检查下是不是图片文件以及大小
1 <script type="text/javascript"> 2 3 function checkFileExt(ext) { 4 if (!ext.match(/.jpg|.gif|.png|.bmp/i)) {//匹配以.jpg或.GIF或....结尾的任意字符串,大写或小写无所谓 5 return false; 6 } 7 return true; 8 } 9 10 function toVaild(){ 11 12 var imagesfile = document.getElementById("imagesfile").value; 13 14 if(imagesfile!=null&&imagesfile.replace(/(^\s*)|(\s*$)/g, "")!=""&&imagesfile!=undefined){ 15 var img = document.getElementById("imagesfile"); 16 var filePath = img.value; 17 var fileExt = filePath.substring(filePath.lastIndexOf(".")) 18 .toLowerCase();//将所有的英文字符转换为小写字母 19 var sizeint=0; 20 if (!checkFileExt(fileExt)) { 21 alert("您上传的文件不是图片,请重新上传!"); 22 return false; 23 } 24 if (img.files && img.files[0]) { 25 sizeint=(img.files[0].size / 1024).toFixed(0); 26 //alert('你选择的文件大小' + (img.files[0].size / 1024).toFixed(0) + "kb"); 27 } else { 28 img.select(); 29 var url = document.selection.createRange().text; 30 try { 31 var fso = new ActiveXObject("Scripting.FileSystemObject"); 32 } catch (e) { 33 alert('如果你用的是ie8以下 请将安全级别调低!'); 34 } 35 sizeint=(fso.GetFile(url).size / 1024).toFixed(0); 36 //alert("文件大小为:" + (fso.GetFile(url).size / 1024).toFixed(0) + "kb"); 37 } 38 if(sizeint>5120){ 39 alert("抱歉 您所上传的图片大于5M 请选择低于5M的图片上传") 40 return false; 41 } 42 } 43 </script>
1 <form action="" method="post" enctype="multipart/form-data" onsubmit="return toVaild()"> 2 <input type="file" id="imagesfile" name="imagesfile" placeholder=""> 3 4 <center><button type="submit" class="am-btn am-btn-danger">提交</button> </center> 5 6 </form>
注:match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值(存放匹配结果的数组),而不是字符串的位置。