程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 詳解springMVC兩種方式完成多文件上傳及效率比擬

詳解springMVC兩種方式完成多文件上傳及效率比擬

編輯:關於JAVA

詳解springMVC兩種方式完成多文件上傳及效率比擬。本站提示廣大學習愛好者:(詳解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解析器停止文件上傳用時辨別為2ms,1ms和2ms。

經過比照這兩種方式我們可以發現運用springMVC停止多文件的效率顯然要比字符流寫入方式效率上要高得多。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved