function submitImg(imgid,formid,imginfo){ var filepath=$("#"+imgid).val(); var extStart=filepath.lastIndexOf("."); if(extStart!=-1){ var ext=filepath.substring(extStart,filepath.length).toUpperCase(); if(ext!=".PNG"&&ext!=".GIF"&&ext!=".JPG"&&ext!=".JPEG"&&ext!=".jpg"&&ext!=".png"&&ext!=".jpeg"&&ext!=".gif"){ $("#"+imginfo).html("上传文件必须为 png,gif,jpeg,jpg格式").css("clour","red").css("size","14px"); return false; }else{ $("#"+imginfo).html(""); } } var options = { url:action="<%=request.getContextPath()%>/customer/uploadBus",//后台的处理,也就是form里的action type:"POST", dataType:"json", //数据格式,有XML,html,json,默认为文本 success:function(msg){ if (msg != "" && msg != null) { if (msg.code == 0) { $.cookie(imgid, msg.url, { expires : 1000*60*60, path : '/' }); $("#"+imginfo).html("身份证正面上传成功").css( "color", "#090"); } else { $("#"+imginfo).html("上传的图片不能大于2M").css( "color", "red"); } } else { $("#"+imginfo).html("图片服务器网络异常").css("color","red"); } } }; $("#"+formid).ajaxSubmit(options); return false;//为了防止刷新 //}); }
html代码
<span class="STYLE21"> <form id="uploadBus" action="<%=request.getContextPath()%>/customer/uploadBus" method="post" enctype="multipart/form-data"> <input type="file" id="business_address" name="business_address" accept="image/*" onchange="submitImg('business_address','uploadBus','imginfo1')"/> </form> </span><span id="imginfo1" style="color: red;"></span>
前提要引入 jquery和jquery.cookie jqueryform
'business_address','uploadBus','imginfo1'分别代表 图片所在input的id form的id 和提示信息的id