熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

jquery的ajaxSubmit()異步上傳圖片並保存表單數據演示代碼

2013-11-15 11:58:24  來源: JSP教程 

  一web (addjsp) 

 代碼如下: <%@page import="comfingerknowprojectvoUserInformation"%>  <%@ page language="java" contentType="text/html; charset=utf"  pageEncoding="utf"%>  <%@ taglib uri="%>  <c:set var="ctx" value="${pageContextrequestcontextPath }" />  <!DOCTYPE html PUBLIC "//WC//DTD HTML Transitional//EN" " <html>  <head>  <meta httpequiv="ContentType" content="text/html; charset=utf">  <title>注冊商圈</title>  <link href="${ctx}/bootstrap/css/bootstrapcss" rel="stylesheet">  <link href="${ctx}/bootstrap/css/bootstrapresponsivecss" rel="stylesheet">  <link rel="stylesheet" href="${ctx}/css/bootstrapresponsivemincss" />  <link rel="stylesheet" href="${ctx}/css/jqueryuicss" />  <link rel="stylesheet" href="${ctx}/css/uniformcss" />  <link rel="stylesheet" href="${ctx}/css/selectcss" />  <link rel="stylesheet" href="${ctx}/css/unicornmaincss" />  <link rel="stylesheet" href="${ctx}/css/commoncss" />  <%  responsesetCharacterEncoding("utf");//這個是設置編碼方式  responsesetContentType("text/html");//這個是設置網頁類型為文本代碼  UserInformation user=null;  String username="";  Integer userId=null;  if(requestgetSession()getAttribute("userinfo")!=null){  user=(UserInformation)requestgetSession()getAttribute("userinfo");  username=usergetUsername();  userId=usergetUserId();  }else{  username="請<a >登錄</a>";  }  %>  </head>  <body>  <div class="headerinner">  <div class="container">  <div class="row">  <div class=" pageheader clearfix">  <div class="span"> <h class="pageheader" style="background:black;"><img alt="fingerknow" src="${ctx}/images/fingerknowpng" width=""><small>中文最大的購物經驗分享平台</small></h> </div>  <div class="span"> <a href="#">首頁</a> |<a href="#">幫助</a></div>  </div>  </div>  </div>  </div>  <div class="container" id="businessEname_div">  <div class="row">  <div class="span"></div>  <div class="span">  <div class="widgetbox">  <div class="widgettitle">  <span class="icon">  <i class="iconalignjustify"></i>  </span>  <h>注冊商圈</h>  </div>    <div class="widgetcontent nopadding">  <form class="formhorizontal" method="post" action="${ctx}/upload/uploaddo" id="uploadImgForm" enctype="multipart/formdata">  <div class="controlgroup" style="border: px solid red;">  <label class="controllabel">*商圈名</label>  <div class="controls" style="width: px;border: px solid red;verticalalign: middle;" >  <input type="text" name="businessName" maxlength="" id="businessName" width="px;"/>  <input type="text" name="userId" maxlength="" value="<%=userId%>" id="userId" width="px;"/>  <div id="businessName_error" ></div>  </div>    </div>  <div class="controlgroup">  <label class="controllabel">*商圈logo</label>  <div class="controls" style="width:px;">  <input type="file" name="file" id="file">  <div id="file_error"></div>  </div>  </div>  <div class="controlgroup">  <label class="controllabel">*商圈英文名</label>  <div class="controls" style="width: px;">  <input type="text" name="businessEname" id="businessEname" />  <div id="businessEname_error"></div>  </div>  </div>  <div class="formactions">  <button type="button" id="imgSave" value="Validate" class="btn btnprimary">提交注冊</button>  </div>  </form>  </div>  </div>  </div>  <div class="span"></div>  </div>  </div>  <div class="container" style="background:white;">  <div class="row">  <div class="span" style="marginleft: %;">  <p>© fingerknowcom <span>|</span><a href="#" rel="nofollow" >隱私條款</a><span>|</span><a href="#" rel="nofollow">服務條款</a><span>|</span><a href="#" rel="nofollow" >粵ICP備</a></p>  </div>  </div>  </div>  <script src="${ctx}/js/jqueryjs"></script>  <script src="${ctx}/js/jqueryformjs"></script>  <script type="text/javascript">  /**  *  * V  */  $(document)ready(function() {    //驗證商圈名  $("#businessName")blur(function(){  var businessName=$("#businessName")val();  if(businessName!=""){  $("#businessName_error")html("<img src=${ctx}/images/success_imggif style=width:px;height:px;/>");  }else{  $("#businessName_error")attr("class""error_div")html("<img src=${ctx}/images/error_imggif style=width:px;height:px;/>"+"商圈名不能為空!");  }    });  //驗證商圈英文名  $("#businessEname")blur(function(){  var businessEname=$("#businessEname")val();  if(businessEname!=""){  $("#businessEname_error")html("<img src=${ctx}/images/success_imggif style=width:px;height:px;/>");  }else{  $("#businessEname_error")attr("class""error_div")html("<img src=${ctx}/images/error_imggif style=width:px;height:px;/>"+"商圈英文名不能為空!");  }  });  //圖片上傳 及數據保存  $("#imgSave")click(function(){  var ext = jpgjpeggifbmppng;  var f=$("#file")val();  if (f== "") {//先判斷是否已選擇了文件  $("#file_error")attr("class""error_div")html("<img src=${ctx}/images/error_imggif style=width:px;height:px;/>"+"請添加商圈logo!");  return false;  }  f = fsubstr(flastIndexOf() + )toLowerCase();  if (extindexOf( + f + ) == ) {  $("#file_error")attr("class""error_div")html("<img src=${ctx}/images/error_imggif style=width:px;height:px;/>"+"圖片格式不正確!");  return false;  }    var options = {  url: "${ctx}/upload/uploaddo"  dataType: json  contentType: "application/json; charset=utf"  success: function(data) {  // data is an object representing the the evaluated json data  // 如果圖片上傳成功則保存表單注冊數據  if(datastatus==""){  var fileName=datafileName;  //alert(fileName);  var businessName=$("#businessName")val();  var userId=$("#userId")val();  var businessEname=$("#businessEname")val();  businessName=encodeURI(businessName);  businessName=encodeURI(businessName);  var urls="${ctx}/business/addBusinessdo?businessName="+businessName+"&businessPic="+fileName+"&businessEname="+businessEname+"&userId="+userId;  $ajax({  type: "post"  url:urls   dataType: "json" /*這句可用可不用沒有影響*/  contentType: "application/json; charset=utf"  success: function (data) {  if(datastatus==""){  alert("注冊成功!");  }else{  alert("注冊失敗!原因是"+datamessage);  }  }  error: function (XMLHttpRequest textStatus errorThrown) {  alert(errorThrown);  }  });  }else{  $("#file_error")attr("class""error_div")html("<img src=${ctx}/images/error_imggif style=width:px;height:px;/>"+datamessage);  }  }  };  // 提交表單  $(#uploadImgForm)ajaxSubmit(options);  });  });  </script>  </body>  </html>    二service(FileUploadControllerjava springMVC 之controller層)   代碼如下: @Controller  @RequestMapping(value = "/upload")  public class FileUploadController {  private Logger logger;  @RequestMapping(value = "uploaddo" method = RequestMethodPOST)  public void fileUpload(HttpServletRequest request HttpServletResponse response) {  Map<String Object> resultMap = new HashMap<String Object>();  String newRealFileName = null;  try {  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  CommonsMultipartFile file = (CommonsMultipartFile) multipartRequestgetFile("file");  // 獲得文件名  String realFileName = filegetOriginalFilename();  if(filegetSize()/>=*){  resultMapput("status" );  resultMapput("message" "圖片不能大於M");  }else{  Systemoutprintln("獲得文件名" + realFileName);  newRealFileName = FileUploadControllergetNowTime() + realFileNamesubstring(realFileNameindexOf(""));  // 獲取路徑  String ctxPath = requestgetSession()getServletContext()getRealPath("//") + "//temp//";  // 創建文件  File dirPath = new File(ctxPath);  if (!dirPathexists()) {  dirPathmkdir();  }  File uploadFile = new File(ctxPath + newRealFileName);  FileCopyUtilscopy(filegetBytes() uploadFile);  requestsetAttribute("files" loadFiles(request));  resultMapput("status" );  resultMapput("fileName" newRealFileName);  }  } catch (Exception e) {  resultMapput("status" );  resultMapput("message" "圖片上傳出錯");  loggerinfo("***** 圖片上傳出錯 *****");  Systemoutprintln(e);  } finally {  PrintWriter out = null;  try {  out = responsegetWriter();  } catch (IOException e) {  eprintStackTrace();  }  //必須設置字符編碼否則返回json會亂碼  responsesetContentType("text/html;charset=UTF");  outwrite(JSONSerializertoJSON(resultMap)toString());  outflush();  outclose();  }  }  }     
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19993.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.