This example is responsible for checking image files, that is, mime type and file size, before sending to the server. When it is called by the onchange handler, the input type file element of the function is passed in the parameters a reference to the element's dom-object and the maximum allowable file size in bytes. After passing the test, the output element, which should be the last child of its parent, should be assigned a class and a message corresponding to the result of the test. http://jsbin.com/kuhicedoya/edit?html,output
<style type="text/css"> .good { font-weight:bold; color:green; } .bad { font-weight:bold; color:red; } </style> <form name="goodsForm" onsubmit="ajax(this,'/goods');" action="javascript:void(0);" method="post" enctype="multipart/form-data"> <div><label for="g5">Image 1:</label><input type="file" id="g5" name="img0" onchange="imgVal(this,10485760);"/><output id="outImg0"></output></div> <div><label for="g6">Image 2:</label><input type="file" id="g6" name="img1" onchange="imgVal(this,10485760);"/><output id="outImg1"></output></div> <div><label for="g7">Image 3:</label><input type="file" id="g7" name="img2" onchange="imgVal(this,10485760);"/><output id="outImg2"></output></div> <div><label for="g8">Image 4:</label><input type="file" id="g8" name="img3" onchange="imgVal(this,10485760);"/><output id="outImg3"></output></div> <div><label for="g9">Image 5:</label><input type="file" id="g9" name="img4" onchange="imgVal(this,10485760);"/><output id="outImg4"></output></div> </form> function imgVal(el,lim) { var doc=el.parentNode.lastChild; if(el.files[0].size<=lim) { var file=new FileReader(); file.onloadend=function(e) { var arr=(new Uint8Array(e.target.result)).subarray(0,4); for(var i=0,l=arr.length,header='';i<l;i++) header+=arr[i].toString(16); var type=false; switch(header){case'89504e47':type='PNG';break;case'47494638':type='GIF';break;case'ffd8ffe0':case'ffd8ffe1':case'ffd8ffe2':type='JPG';break;} if (type) { doc.setAttribute('class','good'); doc.innerHTML=Math.round(el.files[0].size/1024)+'kB'+' '+type; } else { el.value=null; doc.setAttribute('class','bad'); doc.value='Supported image only JPG PNG GIF'; } }; file.readAsArrayBuffer(el.files[0]); } else { el.value=null; doc.setAttribute('class','bad'); doc.value='File size should be less than 10 MB'; } }