Ajax for file and other parameters upload function

Source: Internet
Author: User
Remember the previous period of time, in order to study the Ajax file upload, find a lot of information, in the Internet to see the majority of forms form the way to submit files, for the Ajax way to submit files and also to submit the form of other data, found that not many mentioned, and later, with the help of colleagues, The use of Ajaxfileupload finally completed the file upload and other submissions, and now share to everyone, I hope you can have some help. This article mainly introduces the use of Ajax file and other parameters of the upload function (Java development), very good, with reference value, the need for reference to friends, hope to help everyone.

File Upload:

Operation Steps:

1 Importing the jar package:

When we use file upload, we need to use two jar packages, namely Commons-io and Commons-fileupload, Here I use two versions are 2.4 with 1.3.1 version, need to use JS file with Jar package finally will send everyone a connection (how to expire please direct me to leave a message, I will change in time, thank you).

2 Modifying the configuration file:

When we import the jar package is not enough, we need to use these jar packages, because I was using the SSM framework, So I was in the Application-content.xml configuration of Commonsmultipartresolver, the specific configuration method is as follows:

<bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >   <property name= "maxuploadsize" >    <value>104857600</value>   </property>   <property name= "Maxinmemorysize" >    <value>4096</value>   </property>  </bean >

3 JSP files:

We are familiar with the way form forms are submitted for pricing, but there are many cases where we cannot directly submit them directly using form forms. At this point we need to use Ajax to submit, Ajax has a lot of benefits, such as when we do not need to refresh the page to get a local refresh, we can use Ajax. Here is the JSP page of my form submission, which contains detailed steps and HTML files for JS:

<%@ page language= "java" contenttype= "text/html; CHARSET=GBK "pageencoding=" GBK "%><% @taglib prefix=" C "uri=" Http://java.sun.com/jsp/jstl/core "%><%@ Include file= ". /commons/taglibs.jsp "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

The above code is my project in the actual development of the code used in the process, the specific CSS files and JS files I have deleted, but will not affect the specific operation, you only need to delete the class file when you can. OK, we're talking about the code above. First of all to explain the role of CTX, in our project development process, we require the absolute path must be used, all {CTX} is one of our packaged things, is our server address + port number + project name. When we use it, we only need to refer to the file, which is the <%@ include file= "that is directly used above. /commons/taglibs.jsp "%>, when we use the time directly using the ${ctx}, you can use it directly using their own native address port number and project name. The/resources/new_js/jquery.js in the back is the storage address of the Jqery.js file we are going to use.
In fact, in the above Ajax operation, I am equivalent to do two times the price of Ajax, but at the time of the first commit, back to us to return a parameter, is our file storage path and file name, at the time of the second commit, we put these parameters and other parameters at the same time upload to the background, and save these parameters to the database so that we can use them.

* 4 Backstage Code:

File Upload @requestmapping (value = "/doupload", method = Requestmethod.post, produces = "text/html; Charset=utf-8 ") @ResponseBody public String doupload (httpservletrequest request, httpservletresponse response) throws  IOException {list<string> fileNames = null;   if (Request instanceof Multiparthttpservletrequest) {//Process the uploaded file Logger.info ("===== Go to document type select =====");  FileNames = uploadattachment (Request, "file");  } String url = "";    if (filenames.size () > 0) {for (int i = 0; i < filenames.size (); i++) {url = url + filenames.get (i);    if (I < filenames.size ()-1) {url = url + ","; }}} return URL; }//File Upload Tool class public list<string> uploadattachment (httpservletrequest request, String type) throws IOException {Mul  Tiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request;  list<multipartfile> files = multipartrequest.getfiles (type); Logger.info ("Data length ========>>>>>>>>>>" + FileS.size ());  Calendar now = Calendar.getinstance ();  int year = Now.get (calendar.year);  int month = Now.get (calendar.month) + 1;  String Realpath = Propertiesutil.getproperty ("Realpath");  System.err.println ("realpath=====>>>>>" + Realpath); String Savepath = Request.getsession (). Getservletcontext (). Getrealpath ("/") + "p_image\\" + type + "\ \" + year+ "\ \" + M  Onth + "\ \";  String Savepath = "Government" + File.separator + "image" + File.separator + year+ file.separator + month + file.separator;  Logger.info ("Save path =====>" + Savepath);  list<string> fileNames = new arraylist<string> ();   for (Multipartfile multipartfile:files) {logger.info ("--" + multipartfile.getoriginalfilename ());   String fileName = Multipartfile.getoriginalfilename ();   String prefix = filename.substring (Filename.lastindexof (".") + 1);   String CustName = "" + system.currenttimemillis () + "." + prefix; if (Usedutil.isnotnull (fileName)) {File TargetFile = new File (realpath+savePath, CustName);    FileName = year+ "-" +month+ "-" +filename;     if (!targetfile.exists ()) {targetfile.mkdirs ();    Multipartfile.transferto (targetfile);    } try {} catch (Exception e) {e.printstacktrace ();   } filenames.add (Savepath + custname); }} return fileNames; }//Add Advisory @requestmapping (value = "/addinfo", method = Requestmethod.post) @ResponseBody public Integer Addinfo ( HttpServletRequest request, HttpServletResponse response, @RequestParam String fileUrl) {Infobean bean = new Infobean (  );  if (Usedutil.isnotnull (FILEURL)) {Bean.setimagepath (FILEURL);  } map<string, object> parammap = controllerutil.request2map (request);  Bean.settitle (String) parammap.get ("title");  Bean.setsummary (String) Parammap.get ("Summary");  Bean.setcontent (String) parammap.get ("content");  Bean.settypeid (String) parammap.get ("TypeId"); return Infoservice.insinfo (Bean); }

In the above code we can see, in the first upload process, we first entered into doupload, and then use the Uploadattachment tool class, and upload the file to the server, in the process of uploading, I first did a file unique name operation, is to obtain the current time of the number of milliseconds, although not guaranteed, but to a small amount of concurrency can guarantee that the file name will not be duplicated. Then I wrote the upload address for the file upload path. The advantage of this is that when we want to change the path of the file upload, we can directly modify the. properties file, and the specific way to read the. properties file is described in my other article. Finally, in the process of development, file saving is generally saved to the file server, and the file server is generally in Linux, and in different servers, the path is the use of slash or backslash is different, All I've used here is file.separator instead, File.separator can automatically generate a slash in different systems to get the backslash.

Related Article

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.