Using Ajax to upload files and other parameters (developed in java), ajaxjava

Source: Internet
Author: User
Tags time in milliseconds

Using Ajax to upload files and other parameters (developed in java), ajaxjava

File Upload:

I remember that some time ago, I found a lot of information to study Ajax file uploads. Most of the information I saw on the Internet was submitting files using form forms, when submitting files in Ajax mode and submitting other data in the form, I found that not many of them were mentioned. With the help of my colleagues, I used ajaxfileupload to complete file upload and other submission operations. I hope you can help me.

Procedure:

1. Import the jar package:

When uploading files, we need to use two jar packages: commons-io and commons-fileupload. Here, we use versions 2.4 and 1.3.1 respectively, you need to use the JS file and the jar package, and finally send a connection to everyone (please leave a message if it becomes invalid, and I will change it in time, thank you ).

2. modify the configuration file:

When we import jar packages is not enough, we need to use these jar packages, since I was using the SSM framework, So I configure CommonsMultipartResolver IN THE application-content.xml, the 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 file:

You are familiar with the form price submission method. However, in many cases, you cannot directly submit the form. At this time, we need to use Ajax for submission. Ajax has many advantages. For example, we can use Ajax when we do not need to refresh the page to obtain partial refreshes. The following is the JSP page of my form submission, which contains detailed JS steps and HTML files:

<% @ 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 "> <Html> 

The above code is the code I used during the actual development of the project. I have deleted the specific CSS file and JS file, but it will not affect the specific operation, you only need to delete the class file. Okay, let's talk about the above Code. First of all, let's explain the role of ctx. In our project development process, we need to use absolute paths. All {ctx} is a encapsulated thing, is our server address + port number + project name. When using the file, you only need to reference the file, which is directly used above <% @ include file = ".. /commons/taglibs. jsp "%>. You can use $ {ctx} directly when using it. You can use your local address port number and project name directly. The following/resources/new_js/jquery. js is the storage address of the jqery. js file to be used.
In fact, in the above Ajax operation, I made two Ajax price increases, but at the first submission, the background returns a parameter to us, that is, our file storage path and file name. During the second submission, we uploaded these parameters and other parameters to the background at the same time and saved them to the database, so that we can use it.

* 4 Background 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 ("==== enter the file type and select ===="); fileNames = uploadAttachme Nt (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 {MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) requ Est; 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 (). getServletCon Text (). getRealPath ("/") + "p_image \" + type + "\" + year + "\" + month + "\\"; 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 f IleName = 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 @ 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 code above, we can see that during the first upload of a file, we first enter doUpload, then use the uploadAttachment tool class, and upload the file to the server, during the upload process, I first performed a unique file name operation, that is, to obtain the current time in milliseconds, although not absolutely guaranteed, however, when the concurrency is small, the file name will not be duplicated. Then, I wrote the upload address of the file upload path. properties, the advantage is that when we want to change the File Upload path, we can directly modify it. properties file, and read. the methods of the properties file are described in another article. Finally, during the development process, files are generally stored in the file server, while the file server is generally in Linux, and on different servers, whether the PATH uses a slash or a backslash is different. All files are used here. separator instead, File. separator can automatically generate a backslash in different systems.

The above section describes how to use Ajax to upload files and other parameters (java Development). If you have any questions, please leave a message, the editor will reply to you in a timely manner, and I would like to thank you for your support for the help House website!

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.