大概逻辑是,1、图片单独form、选择上传图片(异步上传,jquery.form.js)
2、后台判断上传图片大小(太大不上传返回提示、或大小可以上传返回上传路径)
3、根据返回路径,判断图片宽高。不符合提示并删除图片、符合提示上传成功
4、上传图片后单击提交数据的form按钮,提交表单(其中有图片路径,存到数据库表中)
html
<form id="multForm" method="post" enctype="multipart/form-data"><span class="L fs_16 gray">应用logo: </span><div class="L app_logo" id="preview"><img id="imghead" src="<%=request.getContextPath()%>/images/app_1.png" width="100%";height="100%"></div><!-- <input type="file" name="file" id="file" class="L pop_inpt"> --><div class="L" style="border:1px solid #c5c5c5;margin-left:10px"><input type="text" name="appLogo" id="appLogo" class="app_logo_name L" readonly="true" style="border-right:none"/><input type="button" value="浏 览" class="app_ll L"/></div><input type="file" name="file" id="file" class="app_file" "/><!-- οnchange="previewImage(this) --></form><form id="editAppForm" οnsubmit="return check()"><input id="id" value="${appId}" type="hidden"/> <input type="text" name="logoPath" id="logoPath" type="hidden" style="display:none"/><p class="app_logo_tip" style=" margin-top: -20px;"><span>仅支持JPG、JPEG、PNG、BMP格式,40*40,文件小于1M</span></p> <div class="clearfix" style="margin-bottom:24px"><span class="L fs_16 gray">应用名称 </span><input name="name" type="text" class="L pop_inpt required"/></div><div class="clearfix" style="margin-bottom:44px"><span class="L fs_16 gray">应用描述 </span><textarea name="note" class="L pop_txt required"></textarea></div><div class="pop_btn_wrapper"><input type="button" value="确定"/><input type="button" value="取消"/></div></form>
js
$(function(){tp.oldPath="";$("#file").change(function (data) {var filepath = $("input[name='file']").val();var extStart = filepath.lastIndexOf(".");var ext = filepath.substring(extStart, filepath.length).toUpperCase();if (ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") {alert("图片限于bmp,png,gif,jpeg,jpg格式");return false;} else { //$("#fileType").text(ext) if(tp.oldPath!=""){tp.deleteFile(path);//删除没用的图片}tp.uploadPoto();//上传图片}return true;});
})
var tp={};
tp.uploadPoto=function (){$('#multForm').ajaxSubmit({success: function (result) {if(result.success){var path = result.data;var img=new Image();img.src=path;img.onload = function(){if(img.width>40||img.heigth>40){ alert("图片不大于40*40"); tp.deleteFile(path);}else{alert("上传成功");tp.oldPath=path;$("#imghead").attr("src",path);$("#logoPath").val(path);$("#appLogo").val(path.split("\\")[path.split("\\").length-1]);}}}else{alert(result.err);} },err:function(){alert("请求失败");},url: ctx + "application/uploadAppLogo",data: $('#multForm').formSerialize(),type: 'POST',dataType: 'json',beforeSubmit: function () {console.log("正在上传图片请稍后");}});
}
//删除图片
tp.deleteFile=function (path){$.ajax({type : "post",url : ctx+"application/deleteAppLog",data:{"filePath":path},dataType:"json",success:function(result){if(result.status=="200"){console.log("删除图片成功");}else{console.log("删除上传文件失败");}},err:function(){console.log("删除上传文件请求失败");}})
}
java
@RequestMapping("/uploadAppLogo")@ResponseBodypublic JsonR uploadAppLogo(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request){//上传文件if(file.getSize()<1*1024*1024){JsonResponse jr = loadFile(file,request,filePath);if(jr.isSuccess()){String path = (String) jr.getData();return JsonR.ok(path);}return JsonR.notOk("上传失败");}else{return JsonR.notOk("上传文件必须小于1M");}}@RequestMapping("/deleteAppLog")@ResponseBodypublic JsonR deleteAppLog(HttpServletRequest request,@RequestParam String filePath){String realPath = request.getSession().getServletContext().getRealPath("");File file = new File(realPath+File.separator+"WEB-INF"+File.separator+filePath);Boolean flag = file.delete();return JsonR.ok(flag);}
private JsonR loadFile(CommonsMultipartFile file,HttpServletRequest request,String path){if (!file.isEmpty()) { try { if(file.getSize()>1*1024*1024){return JsonResponse.notOk("请选择小于1M的文件");}// 拿到输出流,同时重命名上传的文件 //File.separator+"WEB-INF"+File.separator+String realPath = request.getSession().getServletContext().getRealPath("");String filename = new Date().getTime()+ file.getOriginalFilename();FileOutputStream os = new FileOutputStream(realPath+File.separator+"WEB-INF"+File.separator+filePath+File.separator+filename); // 拿到上传文件的输入流 InputStream in = file.getInputStream(); // 以写字节的方式写文件 int b = 0; while((b=in.read()) != -1){ os.write(b); } os.flush(); os.close(); in.close(); //返回文件路径,用于数据库存储return JsonR.ok(filePath+File.separator+filename);} catch (Exception e) { return JsonR.notOk("文件上传失败");} }return JsonR.notOk("文件上传失败");}