(jsp需要引入 :jquery-1.9.0.js、jquery.form.js ) ,jsp页面使用的是bootstrap制作的,看不懂的标签不用管,form表单大同小异。代码比较简陋,只是为了演示使用ajaxSubmit异步上传图片及保存数据,请海含! (参考文献:http://www.jb51.net/shouce/jquery/jquery_api/Plugins/Form/ajaxSubmit.html) 一:web (add.jsp) 复制代码 代码如下: pageEncoding="utf-8"%> 注册商圈 response.setCharacterEncoding("utf-8");//这个是设置编码方式 response.setContentType("text/html");//这个是设置网页类型,为文本代码 UserInformation user=null; String username=""; Integer userId=null; if(request.getSession().getAttribute("userinfo")!=null){ user=(UserInformation)request.getSession().getAttribute("userinfo"); username=user.getUsername(); userId=user.getUserId(); }else{ username="请登录"; } %> 中文最大的购物经验分享平台 首页 |帮助 注册商圈 *商圈名: *商圈logo: *商圈英文名: 提交注册 © 2012 fingerknow.com |隐私条款|服务条款|粤ICP备12003619号-1 <BR>/** <BR>* <BR>* V1.0 <BR>*/ <BR>$(document).ready(function() { <br><br>//验证商圈名 <BR>$("#businessName").blur(function(){ <BR>var businessName=$("#businessName").val(); <BR>if(businessName!=""){ <BR>$("#businessName_error").html("<img src='${ctx}/images/success_img.gif' style="max-width:90%"/ alt="jquery的ajaxSubmit()异步上传图片并保存表单数据演示代码_jquery" >"); <BR>}else{ <BR>$("#businessName_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' style="max-width:90%"/ alt="jquery的ajaxSubmit()异步上传图片并保存表单数据演示代码_jquery" >"+"商圈名不能为空!"); <BR>} <br><br>}); <BR>//验证商圈英文名 <BR>$("#businessEname").blur(function(){ <BR>var businessEname=$("#businessEname").val(); <BR>if(businessEname!=""){ <BR>$("#businessEname_error").html("<img src='${ctx}/images/success_img.gif' style="max-width:90%"/ alt="jquery的ajaxSubmit()异步上传图片并保存表单数据演示代码_jquery" >"); <BR>}else{ <BR>$("#businessEname_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' style="max-width:90%"/ alt="jquery的ajaxSubmit()异步上传图片并保存表单数据演示代码_jquery" >"+"商圈英文名不能为空!"); <BR>} <BR>}); <BR>//图片上传 及数据保存 <BR>$("#imgSave").click(function(){ <BR>var ext = '.jpg.jpeg.gif.bmp.png.'; <BR>var f=$("#file").val(); <BR>if (f== "") {//先判断是否已选择了文件 <BR>$("#file_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' style="max-width:90%"/ alt="jquery的ajaxSubmit()异步上传图片并保存表单数据演示代码_jquery" >"+"请添加商圈logo!"); <BR>return false; <BR>} <BR>f = f.substr(f.lastIndexOf('.') + 1).toLowerCase(); <BR>if (ext.indexOf('.' + f + '.') == -1) { <BR>$("#file_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' style="max-width:90%"/ alt="jquery的ajaxSubmit()异步上传图片并保存表单数据演示代码_jquery" >"+"图片格式不正确!"); <BR>return false; <BR>} <br><br>var options = { <BR>url: "${ctx}/upload/upload.do", <BR>dataType: 'json', <BR>contentType: "application/json; charset=utf-8", <BR>success: function(data) { <BR>// 'data' is an object representing the the evaluated json data <BR>// 如果图片上传成功则保存表单注册数据 <BR>if(data.status=="0"){ <BR>var fileName=data.fileName; <BR>//alert(fileName); <BR>var businessName=$("#businessName").val(); <BR>var userId=$("#userId").val(); <BR>var businessEname=$("#businessEname").val(); <BR>businessName=encodeURI(businessName); <BR>businessName=encodeURI(businessName); <BR>var urls="${ctx}/business/addBusiness.do?businessName="+businessName+"&businessPic="+fileName+"&businessEname="+businessEname+"&userId="+userId; <BR>$.ajax({ <BR>type: "post", <BR>url:urls , <BR>dataType: "json", /*这句可用可不用,没有影响*/ <BR>contentType: "application/json; charset=utf-8", <BR>success: function (data) { <BR>if(data.status=="0"){ <BR>alert("注册成功!"); <BR>}else{ <BR>alert("注册失败!原因是:"+data.message); <BR>} <BR>}, <BR>error: function (XMLHttpRequest, textStatus, errorThrown) { <BR>alert(errorThrown); <BR>} <BR>}); <BR>}else{ <BR>$("#file_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' style="max-width:90%"/ alt="jquery的ajaxSubmit()异步上传图片并保存表单数据演示代码_jquery" >"+data.message); <BR>} <BR>} <BR>}; <BR>// 提交表单 <BR>$('#uploadImgForm').ajaxSubmit(options); <BR>}); <BR>}); <BR> 二:service(FileUploadController.java ----springMVC 之controller层) 复制代码 代码如下: @Controller @RequestMapping(value = "/upload") public class FileUploadController { private Logger logger; @RequestMapping(value = "upload.do", method = RequestMethod.POST) public void fileUpload(HttpServletRequest request, HttpServletResponse response) { Map resultMap = new HashMap(); String newRealFileName = null; try { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file"); // 获得文件名: String realFileName = file.getOriginalFilename(); if(file.getSize()/1024>=5*1024){ resultMap.put("status", 1); resultMap.put("message", "图片不能大于5M"); }else{ System.out.println("获得文件名:" + realFileName); newRealFileName = FileUploadController.getNowTime() + realFileName.substring(realFileName.indexOf(".")); // 获取路径 String ctxPath = request.getSession().getServletContext().getRealPath("//") + "//temp//"; // 创建文件 File dirPath = new File(ctxPath); if (!dirPath.exists()) { dirPath.mkdir(); } File uploadFile = new File(ctxPath + newRealFileName); FileCopyUtils.copy(file.getBytes(), uploadFile); request.setAttribute("files", loadFiles(request)); resultMap.put("status", 0); resultMap.put("fileName", newRealFileName); } } catch (Exception e) { resultMap.put("status", 1); resultMap.put("message", "图片上传出错"); logger.info("***** 图片上传出错 *****"); System.out.println(e); } finally { PrintWriter out = null; try { out = response.getWriter(); } catch (IOException e) { e.printStackTrace(); } //必须设置字符编码,否则返回json会乱码 response.setContentType("text/html;charset=UTF-8"); out.write(JSONSerializer.toJSON(resultMap).toString()); out.flush(); out.close(); } } }