Use Ajax and Spring to implement the file upload function code.

Source: Internet
Author: User

Use Ajax and Spring to implement the file upload function code.

To meet project requirements, develop a web form page that can upload images to the server.

I. Requirements

The Web form page allows you to upload images and other text information through a form.

Ii. Image Upload Process

I have not done this kind of page before, by querying materials. A common practice is to upload images to a file directory on the server, and the server returns the image storage path to the front-end, the front-end submits the image storage path and other form information together to the server. All form information is stored in the database.

Iii. Methods

For project requirements, I will introduce two Image Upload methods. The first is to use ajax to directly upload an image, and the second is to cut the image into a smaller file at the front end, then upload images to the server using ajax, and the server Concatenates the files. (Method 2 is suitable for uploading large files) I will introduce the two methods respectively.

Method 1: upload directly

1 html page

<Pre name = "code" class = "html"> <! DOCTYPE html> 

(2) Call the ajaxfileupload. js library and write an image upload script. The name here is ajaxfileuplaod_implement.js.

<P> </p> <pre name = "code" class = "javascript"> function fileUpload () {var inputObject = $ ("# fileImage "). get (0); if (inputObject. value = "") {alert ("select the image to be uploaded first"); return false;} $. ajaxFileUpload ({url: '/PicSubmit/pic', // server-side request address secureuri: false, // whether a security protocol is required, generally set to false type: 'post ', fileElementId: 'fileimag', // ID of the file upload field dataType: 'text', // the return value type is set to json enctype: 'multipart/form-data ', // be sure to have this parameter. Success: function (data, status) // The server returns the processing function {data = decodeURI (data); // The server uses urlencode to encode Chinese characters, so decoding is required here. The purpose is to prevent Chinese garbled var address = JSON. parse (data); for (var I = 0; I <address. length; I ++) {ajaxfile_onSuccess (address [I]); // The success callback function can be defined by yourself, but note that, write the image storage path returned by the server to </pre> <pre name = "code" class = "javascript"> <span style = "white-space: pre "> </span> // value of The hiden tag. For the method, see the following writeHide function }}, complete: function (xmlHttpRequest) {<span style = "white-space: pre"> </span> // here, replace the File Upload tag in html with the new tag, which I found during development, when After jax executes an upload operation and then selects a file using the file tag, the tag does not respond, </pre> <pre name = "code" class = "javascript"> <span style = "white-space: pre "> </span> // This method is currently used. InputObject. replaceWith ('<input type = "file" id = "fileImage" name = "fileImage"/>') ;}, error: function (data, status, e) // handler for server response failure {// alert ("unable to connect to server ");}})} </pre> <pre name = "code" class = "javascript"> </pre> <pre name = "code" class = "javascript"> function writeHide (data) {<span style = "white-space: pre"> </span> if ($ ("# addressid "). get (0 ). value = "") <span style = "white-space: pre"> </span> {<span style = "White-space: pre"> </span> $ ("# addressid "). get (0 ). value = data. newName; <span style = "white-space: pre"> </span >}< span style = "white-space: pre "> </span> else <span style =" white-space: pre "> </span> {<span style =" white-space: pre "> </span> $ (" # addressid "). get (0 ). value = $ ("# addressid "). get (0 ). value + "," + data. newName; <span style = "white-space: pre" ></ span >}</pre> <p> </p> <p> 3 spring. </p> <p> after completing the preceding two parts The main work is basically over. I used the spring framework in the background. </P> <p> springMVC configuration file: viewspace-servlet.xml </p> <pre name = "code" class = "html"> <? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns =" "Xmlns: xsi =" "Xmlns: p =" "Xmlns: context =" "Xmlns: mvc =" "Xsi: schemaLocation =" Spring-beans-3.1.xsd Spring-mvc-3.1.xsd /Spring-context-3.1.xsd "> <! -- Static resources --> <mvc: resources mapping = "/js/**" location = "/js/"/> <mvc: resources mapping = "/css/**" location = "/css/"/> <mvc: resources mapping = "/image/**" location = "/image/"/> <! -- Scan the web package and apply Spring annotations --> <context: component-scan base-package = "web"/> <bean id = "defaultAnnotationHandlerMapping" class = "org. springframework. web. servlet. mvc. annotation. defaultAnnotationHandlerMapping "/> <bean id =" annotationMethodHandlerAdapter "class =" org. springframework. web. servlet. mvc. annotation. annotationMethodHandlerAdapter "/> <! -- Configure the view parser to parse ModelAndView and string to a specific page --> <bean class = "org. springframework. web. servlet. view. internalResourceViewResolver "p: viewClass =" org. springframework. web. servlet. view. jstlView "p: prefix ="/WEB-INF/jsp/"p: suffix = ". jsp "/> <! -- Enable springMVC to support Image Upload --> <bean id = "multipartResolver" class = "org. springframework. web. multipart. commons. CommonsMultipartResolver"> <! -- Maximum upload size: 1 MB --> <property name = "maxUploadSize" value = "10485760"/> <! -- Default encoding --> <property name = "defaultEncoding" value = "UTF-8"/> <! -- Parsing uploaded files --> <property name = "resolveLazily" value = "true"/> </bean> <! -- SpringMVC throws org. springframework. web. multipart. MaxUploadSizeExceededException when the file upload limit is exceeded. <! -- This exception is thrown by SpringMVC when checking the information of the uploaded file, and has not yet entered the Controller Method --> <bean id = "exceptionResolver" class = "org. springframework. web. servlet. handler. simpleMappingExceptionResolver "> <property name =" exceptionMappings "> <props> <! -- Encounter MaxUploadSizeExceededException exception, automatically jump to/WEB-INF/jsp/error_toobig.jsp page --> <prop key = "org. springframework. web. multipart. maxUploadSizeExceededException "> error_fileupload </prop> </props> </property> </bean> </beans> </pre>. springframework. web. multipart. commons. commonsMultipartResolver is required. Otherwise, the background cannot receive files from the foreground. <P> </p> <br> </p> <p> to prevent Chinese Character transmission problems in file names. </p> <pre name = "code" class = "html"> <? Xml version = "1.0" encoding = "UTF-8"?> <Web-app xmlns: xsi =" "Xmlns =" "Xsi: schemaLocation =" /Web-app_3_0.xsd "version =" 3.0 "> <context-param> <param-name> contextConfigLocation </param-name> <param-value> classpath: applicationContext. xml </param-value> </context-param> <listener-class> org. springframework. web. context. contextLoaderListener </listener-class> </listener> <servlet-name> viewspace </servlet-name> <servlet-class> org. springframework. web. servlet. dispatcherServlet </Servlet-class> </servlet> <servlet-mapping> <servlet-name> viewspace </servlet-name> <url-pattern>/</url-pattern> </ servlet-mapping> <! -- Supports transmitting Chinese characters --> <filter-name> characterEncodingFilter </filter-name> <filter-class> org. springframework. web. filter. characterEncodingFilter </filter-class> <init-param> <param-name> encoding </param-name> <param-value> UTF-8 </param-value> </init- param> <init-param> <param-name> forceEncoding </param-name> <param-value> true </param-value> </init-param> </filter> <filter-mapping> <filter-name> characterEncodingFilter </filter-name> <url-pattern>/* </url-pattern> </filter-mapping> </web -app> </pre> <p> </p> <br> </p>

Next, we will focus on using the following methods in Controller to accept the files worn back from the front-end. <Br>

<pre name="code" class="java"> @RequestMapping(value="/pic")   @ResponseBody   public String submitPic(@RequestParam(value = "filename",required = false) MultipartFile[] fileImage,        HttpServletRequest request){     if(fileImage == null){       return "[]";     }     return picSaveService.savePic(fileImage);   }</pre><br> 

Note that if the multiple attribute is used in the input tag of the front-end html, it indicates that the tag supports uploading multiple images. Then, in the controller parameter list, the file type uses MultipartFile []. Otherwise, if the multiple attribute is not used to upload an image, the controller uses the MultipartFile type for receiving.

<P> <br> </p> <p> after receiving a file, you can store the file. There are many methods. Here is an example: </p> <pre name = "code" class = "java"> public String savePic (MultipartFile [] fileImage) {// rename the image String oldName = ""; String newName = ""; String extension = ""; // name the image SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmssSSS") according to the upload time; // store the information List of each image <PicConfirmData> resultList = new ArrayList <PicConfirmData> (); // obtain the storage path of the image in the configuration file String p Ath = Parameters. getInstance (). getDatabaseProps (). getProperty ("pic_save_dir"); // store the image in the path for (int I = 0; I <fileImage. length; I ++) {System. out. println (fileImage [I]. getOriginalFilename (); oldName = fileImage [I]. getOriginalFilename (); extension = oldName. substring (oldName. lastIndexOf (". "); newName = sdf. format (new Date () + extension; File target = new File (path, newName); if (! Target. exists () {target. mkdirs ();} try {fileImage [I]. transferTo (target);} catch (IllegalStateException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}// record the image storage Information PicConfirmData pic = null; try {// save only the name, the path is known, thus saving the database space // pic = new PicConfirmData (URLEncoder. encode (oldName, "UTF-8"), path + newName); pic = new PicConfirmData (1, URLEncoder. encode (oldName, "UTF-8"), newName ); ResultList. add (pic);} catch (UnsupportedEncodingException e) {e. printStackTrace () ;}} return ToolJson. getJsonFromPicConfirmData (resultList) ;}</pre> the original name of the received image and the name used by the storage are returned to the front-end, the original name is used to output the "Storage successful" prompt on the front-end page. The modified name is used to copy the hiden tag, the content of the hiden tag will be submitted to the server along with other information in the form. With the hiden tag, we can know where the image associated with the form is stored. <Br> <p> </p> <p> Finally, you must submit a form after the image is uploaded. SpringMVC is used to implement the form receiving function. The parameter "address" is used to store the image storage path. </P> <pre name = "code" class = "java"> @ RequestMapping (value = "/form ") public String submitForm (HttpServletRequest request) {String sid = request. getParameter ("name"); String address = request. getParameter ("address"); if (sid! = Null & submiter! = Null & faultTime! = Null & message! = Null & address! = Null) {if (formDataSaveService. saveForm (sid, submiter, message, address, faultTime) {return "ac" ;}} return "error" ;}</pre> <br>

Method 2: front-end cut upload (with additional content) <p> </p>

<p><br> </p> <link rel="stylesheet" href="">            </pre> 

The above is the code for implementing the file upload function using Ajax and Spring introduced by xiaobian. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.