Detailed SPRINGMVC two ways to achieve multiple file upload and efficiency comparison _java

Source: Internet
Author: User
Tags bind character set file upload xmlns

SPRINGMVC implementation of multiple file upload way There are two kinds, one is that we often use the byte stream to upload files, the other is the use of SPRINGMVC packaged parser to upload. These two ways for the realization of multiple file upload efficiency but there is a big gap, below we take a look at these two ways to achieve the way, at the same time compare the efficiency in the end of how much gap.

1. Download the relevant JAR package. the jar that needs to be introduced is outside the SPRINGMVC jar package, Com.springsource.org.apache.commons.fileupload-1.2.0.jar and Com.springsource.org.apache.commons.io-1.4.0.jar also need to be introduced.

2. Configure the Springannotation-servlet.xml file (file name can be customized as long as the name introduced in Web.xml):

<?xml version= "1.0" encoding= "UTF-8"?> <!--Bean head--> <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/context/spring-context-3.0.xsd 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> <!--replaces 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 "class=" Org.springframework.web.servlet.view.InternalResourceViewResolve R "> <property name=" prefix "value="/"></property> <property name=" suffix "value=". JSP ">< /property> </bean> <bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons" . Commonsmultipartresolver "> <property name=" defaultencoding "value=" Utf-8 "></property> <proper Ty name= "maxuploadsize" value= "10485760000" ></property> <property name= "maxinmemorysize" value= "40960" & 
 Gt;</property> </bean> </beans>

3. Configure Web.xml Files:

<?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/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-fi le>index.html</welcome-file> </welcome-file-list> <servlet> <servlet-name>springmvc& Lt;/servlet-name> <!--SPRINGMVC distributor--> <servlet-class>org.springframework.web.servlet.dispatchers Ervlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> & Lt;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> &LT;INIT-PA Ram> <param-name>encoding</param-name> <param-value>UTF-8</param-value> <!--settings You want to use the character set, I'm here with gb18030--> </init-param> <init-param> <param-name>forceencoding</para m-name> <param-value>true</param-value> </init-param> </filter> <filter-ma pping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> <!- -Set the page you want to filter or servlet, configure--> </filter-mapping> <servlet-mapping> <servlet-name>sprin according to your needs 
 gmvc</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" >  

5. Java bean to implement 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& 
     
      lt;files.length;i++) {System.out.println ("FileName---------->" + files[i].getoriginalfilename ()); 
        if (!files[i].isempty ()) {int pre = (int) system.currenttimemillis (); try {//get the output stream while renaming the uploaded file FileOutputStream os = new FileOutputStream ("h:/" + New Date (). GetTime () + F 
          Iles[i].getoriginalfilename ()); 
           
          Get the upload file input stream fileinputstream in = (FileInputStream) files[i].getinputstream (); 
          Write a file in the form of a writing section int b = 0; 
          while ((B=in.read ())!=-1) {os.write (b); 
          } os.flush (); 
       Os.close ();   In.close (); 
          int finaltime = (int) system.currenttimemillis (); 
           
        System.out.println (Finaltime-pre); 
          catch (Exception e) {e.printstacktrace (); 
        System.out.println ("Upload error"); 
  }} return "/success"; @RequestMapping ("/upload2") public String upload2 (httpservletrequest request,httpservletresponse response Throws IllegalStateException, IOException {//Create a generic multi-part parser commonsmultipartresolver multipartresolver = new C 
    Ommonsmultipartresolver (Request.getsession (). Getservletcontext ()); To determine if the request has file uploads, that is, the multi-part Requests if (Multipartresolver.ismultipart (Request)) {///convert to multiple parts of the petition Multiparthttps 
      Ervletrequest multirequest = (multiparthttpservletrequest) request; 
      Get all the filenames in the request iterator<string> iter = Multirequest.getfilenames (); while (Iter.hasnext ()) {//record the time at the start of the upload process to calculate the upload time int pre = (int) System.currenttimemilliS (); 
        Get upload file Multipartfile = Multirequest.getfile (Iter.next ()); 
          if (file!= null) {//Get the file name of the current upload file String myfilename = File.getoriginalfilename (); 
            If the name is not "", it indicates that the file exists, otherwise the file does not exist if (Myfilename.trim ()!= "") {System.out.println (myfilename); 
            Renaming the uploaded filename String filename = "Demoupload" + file.getoriginalfilename (); 
            Define 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 print data, the data comes from the time it takes to upload files in the background, the first picture is used to complete three files on each file with a stream of bytes, and the second picture is used when each file crosses the same file on three identical files using the SPRINGMVC packaged parser:

The byte stream realizes the transfer efficiency of the file upload, and the results show that the three files are 534ms,453ms and 387ms respectively.

File uploads using the SPRINGMVC parser are 2ms,1ms and 2ms respectively.

By contrasting these two approaches, we can see that the efficiency of using SPRINGMVC for multiple files is obviously much more efficient than the character stream write mode.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.