There are two ways to implement multi-file uploading in springMVC. One is to upload files in a byte stream that we often use, and the other is to upload them using a parser wrapped in springMVC. These two methods have a big gap in the efficiency of achieving multi-file upload. Let’s take a look at the implementation methods of these two methods through examples, and compare how big the gap in efficiency exists.
1. Download the relevant jar package. In addition to the jar package of springMVC, com.springsource.org.apache.commons.fileupload-1.2.0.jar and com.springsource.org.apache.commons.io-1.4.0.jar and com.springsource.org.apache.commons.io-1.4.0.jar are also needed.
2. Configure springAnnotation-servlet.xml file (the file name can be customized, as long as it is the same as the name introduced in web.xml):
<?xml version="1.0" encoding="UTF-8"?> <!-- Bean header--> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <!-- Annotation scan package --> <context:component-scan base-package="com.tgb.web.controller.annotation"></context:component-scan> <!-- Replace the following two lines of code --> <mvc:annotation-driven/> <!-- Static resource access --> <mvc:resources location="/img/" mapping="/img/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <bean id="viewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="multipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <property name="maxUploadSize" value="10485760000"></property> <property name="maxInMemorySize" value="40960"></property> </bean> </beans>
3. Configure the web.xml file:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springMVC1</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <servlet> <servlet-name>springMVC</servlet-name> <!-- springMVC distributor--> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/springAnnotation-servlet.xml</param-value> </init-param> <!-- Indicates that the Servlet is initialized when Tomcat is started --> <load-on-startup>1</load-on-startup> </servlet> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> <!--Set the character set you want to use. I am using GB18030--> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> <!--Set the page or servlet you want to filter, configure it according to your needs--> </filter-mapping> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
4. jsp page code:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript" src="../js/jquery-1.7.2.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> i = 1; j = 1; $(document).ready(function(){ $("#btn_add1").click(function(){ document.getElementById("newUpload1").innerHTML+='<div id="div_'+i+'"><input name="file" type="file" /><input type="button" value="Delete" onclick="del_1('+i+')"/></div>'; i = i + 1; }); $("#btn_add2").click(function(){ document.getElementById("newUpload2").innerHTML+='<div id="div_'+j+'"><input name="file_'+j+'" type="file" /><input type="button" value="delete" onclick="del_2('+j+')"/></div>'; j = j + 1; }); }); function del_1(o){ document.getElementById("newUpload1").removeChild(document.getElementById("div_"+o)); } function del_2(o){ document.getElementById("newUpload2").removeChild(document.getElementById("div_"+o)); } </script> </head> <body> <h1>springMVC byte stream input upload file</h1> <form name="userForm1" action="/springMVC7/file/upload" enctype="multipart/form-data" method="post"> <div id="newUpload1"> <input type="file" name="file"> </div> <input type="button" id="btn_add1" value="add one line" > <input type="submit" value="upload" > </form> <br> <hr align="left" color="#FF0000" size="3"> <br> <h1>springMVC wrapper class upload file</h1> <form name="userForm2" action="/springMVC7/file/upload2" enctype="multipart/form-data" method="post""> <div id="newUpload2"> <input type="file" name="file"> </div> <input type="button" id="btn_add2" value="add one line"> <input type="submit" value="upload" > </form> </body> </html>5. Java bean that implements the upload function:
package com.tgb.web.controller.annotation.upload; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Date; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.swing.filechooser.FileNameExtensionFilter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ModelAndView; import com.tgb.web.controller.entity.User; @Controller @RequestMapping("/file") public class UploadController { @RequestMapping("/upload" ) public String addUser(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request){ for(int i = 0;i<files.length;i++){ System.out.println("fileName----------->" + files[i].getOriginalFilename()); if(!files[i].isEmpty()){ int pre = (int) System.currentTimeMillis(); try { //Get the output stream and rename the uploaded file FileOutputStream os = new FileOutputStream("H:/" + new Date().getTime() + files[i].getOriginalFilename()); //Get the input stream of the uploaded file FileInputStream in = (FileInputStream) files[i].getInputStream(); //Write the file int b = 0; while((b=in.read()) != -1){ os.write(b); } os.flush(); os.close(); in.close(); int final time = (int) System.currentTimeMillis(); System.out.println(finaltime - pre); } catch (Exception e) { e.printStackTrace(); System.out.println("UploadError"); } } } return "/success"; } @RequestMapping("/upload2" ) public String upload2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException { //Create a general multipart resolver CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //Defend whether the request has file upload, that is, if(multipartResolver.isMultipart(request)){ //Convert to multipart request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; //Get all file names in the request Iterator<String> iter = multiRequest.getFileNames(); while(iter.hasNext()){ //Record the time at the beginning of the upload process and use it to calculate the upload time int pre = (int) System.currentTimeMillis(); //Get the upload file MultipartFile file = multiRequest.getFile(iter.next()); if(file != null){ //Get the file name of the currently uploaded file String myFileName = file.getOriginalFilename(); //If the name is not "", it means that the file exists, otherwise it means that the file does not exist if(myFileName.trim()) !=""){ System.out.println(myFileName); //Rename the uploaded file name String fileName = "demoUpload" + file.getOriginalFilename(); //Define the upload path String path = "H:/" + fileName; File localFile = new File(path); file.transferTo(localFile); } } //Record the time after uploading the file int finaltime = (int) System.currentTimeMillis(); System.out.println(finaltime - pre); } } return "/success"; } @RequestMapping("/toUpload" ) public String toUpload() { return "/upload"; } } 6. Finally, look at the background printing data. The data comes from the time it takes to upload files printed in the background. The first picture is the time it takes to upload each file in three files using byte stream writing. The second picture is the time it takes to upload each file in three identical files using a parser wrapped in springMVC:
Byte stream realizes the delivery efficiency of file upload, and the results show that the time required to pass the three files is 534ms, 453ms and 387ms respectively.
The time to upload files using springMVC parser is 2ms, 1ms and 2ms respectively.
By comparing these two methods, we can find that using springMVC for multiple files is obviously much more efficient than writing characters.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.