欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解springMVC两种方式实现多文件上传及效率比较

程序员文章站 2024-03-11 14:24:43
springmvc实现多文件上传的方式有两种,一种是我们经常使用的以字节流的方式进行文件上传,另外一种是使用springmvc包装好的解析器进行上传。这两种方式对于实现多文...

springmvc实现多文件上传的方式有两种,一种是我们经常使用的以字节流的方式进行文件上传,另外一种是使用springmvc包装好的解析器进行上传。这两种方式对于实现多文件上传效率上却有着很大的差距,下面我们通过实例来看一下这两种方式的实现方式,同时比较一下在效率上到底存在着多大的差距。

1.下载相关jar包。需要引入的jar出了springmvc的jar包外,还需要引入com.springsource.org.apache.commons.fileupload-1.2.0.jar和com.springsource.org.apache.commons.io-1.4.0.jar。

2.配置springannotation-servlet.xml文件(文件名称可以自定义,只要和web.xml中引入的名称一样即可):

<?xml version="1.0" encoding="utf-8"?> 
<!-- bean头部 --> 
<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"> 
   
  <!-- 注解扫描包 --> 
  <context:component-scan base-package="com.tgb.web.controller.annotation"></context:component-scan> 
  <!-- 代替下面的两行代码 --> 
  <mvc:annotation-driven/> 
  
  <!-- 静态资源访问 --> 
  <mvc:resources location="/img/" mapping="/img/**"/> 
  <mvc:resources location="/js/" mapping="/js/**"/> 
   
   
  <bean id="viewresolver" class="org.springframework.web.servlet.view.internalresourceviewresolver"> 
    <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>  
    <property name="maxuploadsize" value="10485760000"></property> 
    <property name="maxinmemorysize" value="40960"></property> 
  </bean> 
</beans> 

3. 配置web.xml文件:

<?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-file>index.html</welcome-file> 
 </welcome-file-list> 
  
 <servlet> 
   <servlet-name>springmvc</servlet-name> 
   <!-- springmvc的分发器 --> 
   <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> 
   <!-- 表示当tomcat已启动的时候初始化这个servlet --> 
   <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> <!--设置你想用的字符集,我这里用的是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> <!--设置你想过滤的页面或者是servlet,根据自己的需要配置-->  
 </filter-mapping>  
  
 <servlet-mapping> 
  <servlet-name>springmvc</servlet-name> 
  <url-pattern>/</url-pattern> 
 </servlet-mapping> 
</web-app> 

4. jsp页面代码:

<%@ 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="删除" 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="删除" 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字节流输入上传文件</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="增加一行" > 
    <input type="submit" value="上传" > 
  </form>  
  <br> 
  <br> 
  <hr align="left" width="60%" color="#ff0000" size="3"> 
  <br> 
  <br> 
   <h1>springmvc包装类上传文件</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="增加一行" > 
    <input type="submit" value="上传" > 
     
     
  </form>  
</body> 
</html> 

5.实现上传功能的java bean:

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 { 
          //拿到输出流,同时重命名上传的文件 
          fileoutputstream os = new fileoutputstream("h:/" + new date().gettime() + files[i].getoriginalfilename()); 
          //拿到上传文件的输入流 
          fileinputstream in = (fileinputstream) files[i].getinputstream(); 
           
          //以写字节的方式写文件 
          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("上传出错"); 
        } 
    } 
    } 
    return "/success"; 
  } 
   
   
  @requestmapping("/upload2" ) 
  public string upload2(httpservletrequest request,httpservletresponse response) throws illegalstateexception, ioexception { 
    //创建一个通用的多部分解析器 
    commonsmultipartresolver multipartresolver = new commonsmultipartresolver(request.getsession().getservletcontext()); 
    //判断 request 是否有文件上传,即多部分请求 
    if(multipartresolver.ismultipart(request)){ 
      //转换成多部分request  
      multiparthttpservletrequest multirequest = (multiparthttpservletrequest)request; 
      //取得request中的所有文件名 
      iterator<string> iter = multirequest.getfilenames(); 
      while(iter.hasnext()){ 
        //记录上传过程起始时的时间,用来计算上传时间 
        int pre = (int) system.currenttimemillis(); 
        //取得上传文件 
        multipartfile file = multirequest.getfile(iter.next()); 
        if(file != null){ 
          //取得当前上传文件的文件名称 
          string myfilename = file.getoriginalfilename(); 
          //如果名称不为“”,说明该文件存在,否则说明该文件不存在 
          if(myfilename.trim() !=""){ 
            system.out.println(myfilename); 
            //重命名上传后的文件名 
            string filename = "demoupload" + file.getoriginalfilename(); 
            //定义上传路径 
            string path = "h:/" + filename; 
            file localfile = new file(path); 
            file.transferto(localfile); 
          } 
        } 
        //记录上传该文件后的时间 
        int finaltime = (int) system.currenttimemillis(); 
        system.out.println(finaltime - pre); 
      } 
       
    } 
    return "/success"; 
  } 
   
  @requestmapping("/toupload" )  
  public string toupload() { 
     
    return "/upload"; 
  } 
   
} 

6.最后看后台打印数据,数据来源于后台打印的上传文件所用的时间,第一幅图片是使用字节流写入方式完成三个文件上传中每个文件用时,第二幅图片是使用springmvc包装好的解析器进行的三个相同的文件上传中每个文件的用时:

字节流实现文件上传的传递效率,结果显示传递三个文件用时分别为534ms,453ms和387ms。

详解springMVC两种方式实现多文件上传及效率比较

使用springmvc解析器进行文件上传用时分别为2ms,1ms和2ms。

详解springMVC两种方式实现多文件上传及效率比较

通过对比这两种方式我们可以发现使用springmvc进行多文件的效率显然要比字符流写入方式效率上要高得多。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。