jquery ajaxsubmit () upload pictures asynchronously and save form data demo code

Source: Internet
Author: User
Tags button type json

  One: Web (add.jsp)  

  Code as follows: <% @page import= "com.fingerknow.project.vo.UserInformation"%>  <%@ page language= "Java" Contenttype= "text/html; Charset=utf-8 "  pageencoding=" Utf-8 "%>  <%@ taglib uri=" Http://java.sun.com/jsp/jstl/core "prefix=" C "%>  <c:set var=" CTX "value=" ${pagecontext.request.contextpath} "/>  <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >  <html >  <head>  <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">  <title> registered Business Circle </title>  <link href=" ${ctx}/bootstrap/css/bootstrap.css " Rel= "stylesheet" >  <link href= "${ctx}/bootstrap/css/bootstrap-responsive.css" rel= "stylesheet" >   <link rel= "stylesheet" href= "${ctx}/css/bootstrap-responsive.min.css"/>  <link rel= "stylesheet" "Href=" ${ctx}/css/jquery-ui.css "/>  <link rel=" stylesheet "href=" ${ctx}/css/uniform.css "/>&N"Bsp <link rel= "stylesheet" href= "${ctx}/css/select2.css"/>  <link rel= "stylesheet" href= "${ctx}/css/" Unicorn.main.css "/>  <link rel= stylesheet" href= "${ctx}/css/common.css"/>  <%  Response.setcharacterencoding ("Utf-8");//This is to set the encoding mode   Response.setcontenttype ("text/html");//This is to set the page type, for the text code   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= "please <a href=" http:/ /localhost:8080/fk/test/login.jsp ' > Login </a> '; } %>  </head>  <body>   <div class= "Header-inner" >  <div class= "container" >  <div class= "Row" >  < Div class= "Page-header clearfix" >  <div class= "Span11" > <h1 class= "Page-header"Style= "Background:black;" ><img alt= "Fingerknow" src= "${ctx}/images/fingerknow.png" "width=" "><small> Chinese largest shopping experience sharing platform </small ></h1> </div>  <div class= "Span1" > <a href= "#" > Home </a> |<a href= "#" > Help < /a></div>  </div>  </div>  </div>  </div>  <div class= " Container "id=" Businessename_div ">  <div class=" Row ">  <div class=" Span1 "></div>   <div class= "Span10" >  <div class= "Widget-box" >  <div class= "Widget-title" >  <span class= "icon" >  <i class= "icon-align-justify" ></i>  </span>  <h5> Registered Business Circle </h5>  </div>    <div class= "widget-content nopadding" >  <form class= " Form-horizontal "method=" post "action=" ${ctx}/upload/upload.do "id=" Uploadimgform "enctype=" Multipart/form-data " >  <div class= "Control-group" style= "border:0px sOlid Red; " >  <label class= "Control-label" >* Business Circle name:</label>  <div class= "Controls" style= "width:350px" border:0px solid red;vertical-align:middle; ">  <input type=" text "name=" BusinessName "maxlength=" "id=" BusinessName "width=" 200px; " />  <input type= "text" name= "userId" maxlength= "value=" <%=userId%> "id=" UserId "width=" 200px; />  <div id= "Businessname_error" ></div>  </div>    </div>  < Div class= "Control-group" >  <label class= "Control-label" >* Business Circle logo:</label>  <div class= " Controls "style=" width:350px; " >  <input type= "file" name= "file" id= "file" >  <div id= "File_error" ></div>  </ div>  </div>  <div class= "Control-group" >  <label class= "Control-label" >* Business Circle English Name: </label>  <div class= "Controls" style= "width:350px;" >  <input type= "text" Name= "Businessename"Id=" Businessename "/>  <div id=" Businessename_error "></div>  </div>  </div >  <div class= "form-actions" >  <button type= "button" id= "Imgsave" value= "Validate" class= "BTN" Btn-primary "> Submit registration </button>  </div>  </form>  </div>  </div>   </div>  <div class= "Span1" ></div>  </div>  </div>  <div Class= "Container" style= "background:white;" >  <div class= "Row" >  <div class= "Span12" style= "margin-left:25%"; >  <p>©2012 fingerknow.com <span>|</span><a href= "#" rel= "nofollow" > Privacy Policy </a> <span>|</span><a href= "#" rel= "nofollow" > Terms of Service </a><span>|</span><a href= "#" Rel= "nofollow" > Guangdong ICP 备 12,003,619th -1</a></p>  </div>  </div>  </div>   <script src= "${ctx}/js/jquery-1.9.0.js" ></script>  <script src= "${ctx}/js/jquery.form.js" ></script>  <script type= "Text/javascript" >  /**  *  * v1.0  */  $ (document). Ready (function () {   //Verify Business Name   $ ("# BusinessName "). blur (function () {  var businessname=$ (" #businessName "). Val ();  if (businessname!=" ") {   $ ("#businessName_error"). HTML ("<img src= ' ${ctx}/images/success_img.gif ' style= ' width:15px;height:15px;") /> "); }else{  $ (" #businessName_error "). attr (" Class "," Error_div "). HTML (" <img src= "${ctx}/images/ Error_img2.gif ' style= ' width:15px;height:15px; ' /> "+" Business Circle name can not be empty! "); }   }); //validation Business Circle English name   $ (" #businessEname "). blur (function () {  var businessename=$ (" # Businessename "). Val ();  if (businessename!=" ") {  $ (" #businessEname_error "). HTML (" <img src= "${ctx}/ Images/success_img.gif ' style= ' width:15px;height:15px; ' /> "); }else{  $ (" #businessEname_error "). attr (" Class "," Error_div "). HTML (" <img src= "${cTx}/images/error_img2.gif ' style= ' width:15px;height:15px; ' /> "+" Business Circle English name can not be empty! "); } }); //image upload and data save   $ (" #imgSave "). Click (function () {  var ext = '. Jpg.jpeg.gif.bmp.png.   var f=$ ("#file"). Val ();  if (f== "") {//Determine if the file   $ ("#file_error") is selected first. attr ("Class", "Error_div"). html ("<img src= ' ${ctx}/images/error_img2.gif ' style= ' width:15px;height:15px;") /> "+" Please add the Business Circle logo! ");  return false; }  f = f.substr (F.lastindexof ('. ') + 1). toLowerCase ();  if (Ext.indexof ('. ' + f + '. ') = = 1) {  $ ("#file_error"). attr ("Class", "Error_div"). HTML (" <img src= ' ${ctx}/images/error_img2.gif ' style= ' width:15px;height:15px; /> "+" picture format is not correct! ");  return false; }    var options = {  URL:" ${ctx}/upload/upload.do ",  dataType: ' JSON ',   ContentType: "Application/json; Charset=utf-8 ",  success:function (data) { //' data ' is an object representing the ' evaluated JSON DATA&NBSP ; Save the form registration data if the picture is uploaded successfully  if (data.status== "0") {  var filename=data.filename; //alert (fileName);  var businessname=$ ("# BusinessName "). Val ();  var userid=$ (" #userId "). Val ();  var businessename=$ (" #businessEname "). Val ();   Businessname=encodeuri (BusinessName);  Businessname=encodeuri (businessname);  var urls= "${ctx}/ Business/addbusiness.do?businessname= "+businessname+" &businesspic= "+filename+" &businessEname= "+ Businessename+ "&userid=" +userid;  $.ajax ({  type: "POST",  url:urls the,  dataType: "JSON",/* This sentence can not be used, does not affect */  contentType: "Application/json; Charset=utf-8 ",  success:function (data) {  if (data.status==" 0 ") {  alert (" Registered success! ");  }else{  alert ("Registration failed!) The reason is:" +data.message "; } },  error:function (XMLHttpRequest, Textstatus, Errorthrown) {  alert (errorthrown); } }); }else{  $ ("#file_error"). attr (" Class "," Error_div "). HTML (" <img src= ' ${ctx}/images/error_img2.gif ' style= ' Widt ")h:15px;height:15px; ' /> "+data.message"; } } }; //Submitting form   $ (' #uploadImgForm ') ajaxsubmit (options); });  });  </script>  </body>  </html>    II: Service ( Fileuploadcontroller.java----SPRINGMVC Controller layer)     code as follows: @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<string, object> resultmap = new hashmap<string, object> ();  String newrealfilename = null;&nb Sp Try {  multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request;  Commonsmultipartfile file = (commonsmultipartfile) multipartrequest.getfile ("file"); //get filename:  String Realfilename = File.getoriginalfilename ();  if (File.getsize ()/1024>=5*1024) {  resultmap.put ("status", 1);  resultmap.put ("message", "picture cannot be greater than 5M"); }else{  SYSTEM.OUT.PRINTLN ("Get filename:" + realfilename);  newrealfilename = fileuploadcontroller.getnowtime () + Realfilename.substring (Realfilename.indexof ("."));  //Get path   String Ctxpath = Request.getsession (). Getservletcontext (). Getrealpath ("//") + "//temp//"; // Create files   File Dirpath = new file (Ctxpath);  if (!dirpath.exists ()) {  Dirpath.mkdir (); }  file Uplo Adfile = 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 "," The picture is out of error ");  Logger.info (" the wrong * * * * * * * * * * on the picture * * * ");  System.out.println (e); } finally {  PrintWriter out = null;  try {&nbsP out = Response.getwriter (); } catch (IOException e) {  e.printstacktrace (); } //must set character encoding. Otherwise, JSON will be garbled   Response.setcontenttype ("Text/html;charset=utf-8");  out.write Jsonserializer.tojson ( RESULTMAP). toString ());  Out.flush ();  out.close (); } } }     

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.