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。所有的jar包可以通过“点击这里”进行下载。

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

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Bean头部 -->
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xmlns:context="http://www.springframework.org/schema/context"
  8. xmlns:util="http://www.springframework.org/schema/util"
  9. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  10. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
  11. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
  12. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
  13. <!-- 注解扫描包 -->
  14. <context:component-scan base-package="com.tgb.web.controller.annotation"></context:component-scan>
  15. <!-- 代替下面的两行代码 -->
  16. <mvc:annotation-driven/>
  17. <!-- 静态资源访问 -->
  18. <mvc:resources location="/img/" mapping="/img/**"/>
  19. <mvc:resources location="/js/" mapping="/js/**"/>
  20. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  21. <property name="prefix" value="/"></property>
  22. <property name="suffix" value=".jsp"></property>
  23. </bean>
  24. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  25. <property name="defaultEncoding" value="utf-8"></property>
  26. <property name="maxUploadSize" value="10485760000"></property>
  27. <property name="maxInMemorySize" value="40960"></property>
  28. </bean>
  29. </beans>

3. 配置web.xml文件:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3. <display-name>springMVC1</display-name>
  4. <welcome-file-list>
  5. <welcome-file>index.html</welcome-file>
  6. </welcome-file-list>
  7. <servlet>
  8. <servlet-name>springMVC</servlet-name>
  9. <!-- springMVC的分发器 -->
  10. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11. <init-param>
  12. <param-name>contextConfigLocation</param-name>
  13. <param-value>classpath*:config/springAnnotation-servlet.xml</param-value>
  14. </init-param>
  15. <!-- 表示当Tomcat已启动的时候初始化这个Servlet -->
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18. <filter>
  19. <filter-name>encodingFilter</filter-name>
  20. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  21. <init-param>
  22. <param-name>encoding</param-name>
  23. <param-value>UTF-8</param-value> <!--设置你想用的字符集,我这里用的是GB18030-->
  24. </init-param>
  25. <init-param>
  26. <param-name>forceEncoding</param-name>
  27. <param-value>true</param-value>
  28. </init-param>
  29. </filter>
  30. <filter-mapping>
  31. <filter-name>encodingFilter</filter-name>
  32. <url-pattern>/*</url-pattern> <!--设置你想过滤的页面或者是Servlet,根据自己的需要配置-->
  33. </filter-mapping>
  34. <servlet-mapping>
  35. <servlet-name>springMVC</servlet-name>
  36. <url-pattern>/</url-pattern>
  37. </servlet-mapping>
  38. </web-app>

4. jsp页面代码:

[html] view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <script type="text/javascript" src="../js/jquery-1.7.2.js"></script>
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  8. <title>Insert title here</title>
  9. <script type="text/javascript">
  10. i = 1;
  11. j = 1;
  12. $(document).ready(function(){
  13. $("#btn_add1").click(function(){
  14. document.getElementById("newUpload1").innerHTML+='<div id="div_'+i+'"><input  name="file" type="file"  /><input type="button" value="删除"  onclick="del_1('+i+')"/></div>';
  15. i = i + 1;
  16. });
  17. $("#btn_add2").click(function(){
  18. document.getElementById("newUpload2").innerHTML+='<div id="div_'+j+'"><input  name="file_'+j+'" type="file"  /><input type="button" value="删除"  onclick="del_2('+j+')"/></div>';
  19. j = j + 1;
  20. });
  21. });
  22. function del_1(o){
  23. document.getElementById("newUpload1").removeChild(document.getElementById("div_"+o));
  24. }
  25. function del_2(o){
  26. document.getElementById("newUpload2").removeChild(document.getElementById("div_"+o));
  27. }
  28. </script>
  29. </head>
  30. <body>
  31. <h1>springMVC字节流输入上传文件</h1>
  32. <form name="userForm1" action="/springMVC7/file/upload" enctype="multipart/form-data" method="post">
  33. <div id="newUpload1">
  34. <input type="file" name="file">
  35. </div>
  36. <input type="button" id="btn_add1" value="增加一行" >
  37. <input type="submit" value="上传" >
  38. </form>
  39. <br>
  40. <br>
  41. <hr align="left" width="60%" color="#FF0000" size="3">
  42. <br>
  43. <br>
  44. <h1>springMVC包装类上传文件</h1>
  45. <form name="userForm2" action="/springMVC7/file/upload2" enctype="multipart/form-data" method="post"">
  46. <div id="newUpload2">
  47. <input type="file" name="file">
  48. </div>
  49. <input type="button" id="btn_add2" value="增加一行" >
  50. <input type="submit" value="上传" >
  51. </form>
  52. </body>
  53. </html>

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

[java] view plaincopy
  1. package com.tgb.web.controller.annotation.upload;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.PrintWriter;
  7. import java.io.UnsupportedEncodingException;
  8. import java.net.URLDecoder;
  9. import java.util.Date;
  10. import java.util.Iterator;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import javax.swing.filechooser.FileNameExtensionFilter;
  14. import org.springframework.stereotype.Controller;
  15. import org.springframework.web.bind.annotation.RequestMapping;
  16. import org.springframework.web.bind.annotation.RequestMethod;
  17. import org.springframework.web.bind.annotation.RequestParam;
  18. import org.springframework.web.multipart.MultipartFile;
  19. import org.springframework.web.multipart.MultipartHttpServletRequest;
  20. import org.springframework.web.multipart.commons.CommonsMultipartFile;
  21. import org.springframework.web.multipart.commons.CommonsMultipartResolver;
  22. import org.springframework.web.servlet.ModelAndView;
  23. import com.tgb.web.controller.entity.User;
  24. @Controller
  25. @RequestMapping("/file")
  26. public class UploadController {
  27. @RequestMapping("/upload"   )
  28. public String addUser(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request){
  29. for(int i = 0;i<files.length;i++){
  30. System.out.println("fileName---------->" + files[i].getOriginalFilename());
  31. if(!files[i].isEmpty()){
  32. int pre = (int) System.currentTimeMillis();
  33. try {
  34. //拿到输出流,同时重命名上传的文件
  35. FileOutputStream os = new FileOutputStream("H:/" + new Date().getTime() + files[i].getOriginalFilename());
  36. //拿到上传文件的输入流
  37. FileInputStream in = (FileInputStream) files[i].getInputStream();
  38. //以写字节的方式写文件
  39. int b = 0;
  40. while((b=in.read()) != -1){
  41. os.write(b);
  42. }
  43. os.flush();
  44. os.close();
  45. in.close();
  46. int finaltime = (int) System.currentTimeMillis();
  47. System.out.println(finaltime - pre);
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. System.out.println("上传出错");
  51. }
  52. }
  53. }
  54. return "/success";
  55. }
  56. @RequestMapping("/upload2"  )
  57. public String upload2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
  58. //创建一个通用的多部分解析器
  59. CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
  60. //判断 request 是否有文件上传,即多部分请求
  61. if(multipartResolver.isMultipart(request)){
  62. //转换成多部分request
  63. MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
  64. //取得request中的所有文件名
  65. Iterator<String> iter = multiRequest.getFileNames();
  66. while(iter.hasNext()){
  67. //记录上传过程起始时的时间,用来计算上传时间
  68. int pre = (int) System.currentTimeMillis();
  69. //取得上传文件
  70. MultipartFile file = multiRequest.getFile(iter.next());
  71. if(file != null){
  72. //取得当前上传文件的文件名称
  73. String myFileName = file.getOriginalFilename();
  74. //如果名称不为“”,说明该文件存在,否则说明该文件不存在
  75. if(myFileName.trim() !=""){
  76. System.out.println(myFileName);
  77. //重命名上传后的文件名
  78. String fileName = "demoUpload" + file.getOriginalFilename();
  79. //定义上传路径
  80. String path = "H:/" + fileName;
  81. File localFile = new File(path);
  82. file.transferTo(localFile);
  83. }
  84. }
  85. //记录上传该文件后的时间
  86. int finaltime = (int) System.currentTimeMillis();
  87. System.out.println(finaltime - pre);
  88. }
  89. }
  90. return "/success";
  91. }
  92. @RequestMapping("/toUpload" )
  93. public String toUpload() {
  94. return "/upload";
  95. }
  96. }

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

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


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


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

springMVC两种方式实现多文件上传及效率比较相关推荐

  1. 【手把手教】Android开发两种方式实现图片的上传下载

    Android 图片上传的应用场景 在Android开发中,很多时候我们需要进行图片,文件的上传下载,最直接的一个应用场景就是用户头像的保存与切换,以及像即时通讯中的图片发送等任何在App中设计图片的 ...

  2. 04springMVC结构,mvc模式,spring-mvc流程,spring-mvc的第一个例子,三种handlerMapping,几种控制器,springmvc基于注解的开发,文件上传,拦截器,s

     1. Spring-mvc介绍 1.1市面上流行的框架 Struts2(比较多) Springmvc(比较多而且属于上升的趋势) Struts1(即将被淘汰) 其他 1.2  spring-mv ...

  3. 运行python程序的两种方式交互式和文件式_Python基础知识2

    运行Python程序的两种方式 小白学习,如有错误欢迎指点 一.每位小白写的第一个Python程序 1.运行Python程序的两种方式 1.1 交互式模式(即时对话) 打开cmd,打开Python解释 ...

  4. 运行python程序的两种方式交互式和文件式_教你如何编写、保存与运行 Python 程序...

    第一步 接下来我们将看见如何在 Python 中运行一个传统的"Hello World"程序.Python教程本章将会教你如何编写.保存与运行 Python 程序. 通过 Pyth ...

  5. 运行python程序的两种方式交互式和文件式_执行Python程序的两种方式

    交互式(了解) 交互式环境下,敲完一条命令按下enter键马上能看到结果,调试程序方便.程序无法永久保存,关掉cmd窗口数据就消失了. 命令行式(了解) 打开文本编辑器,在文本编辑器中写入一串字符. ...

  6. SpringMVC之表单提交===③===多文件上传表单

    上文简单介绍了springmvc单文件上传表单 ,本文继续介绍多文件上传表单.包含单文件上传的表单已经能够满足大部分功能需求,但任然不够完善.实际业务中可能会包含多个文件同时上传,例如:商家在电商平台 ...

  7. springMVC结合jersey实现跨服务器文件上传

    除了spring相关的依赖依赖,我们需要添加jersey的两个相关依赖,版本信息可以不同. <dependency><groupId>com.sun.jersey</gr ...

  8. SpringBoot2.0 基础案例(14):基于Yml配置方式,实现文件上传逻辑

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.文件上传 文件上传是项目开发中一个很常用的功能,常见的如头像上 ...

  9. 两种方式读取Json文件 数据

    首先下载LitJson.dll 文件,并将其拖入 Unity项目中的 的 Assets/Plugins目录中 其次在你的Unity项目中创建好Assets/StreamingAssets文件夹,用于存 ...

最新文章

  1. 我也说说Emacs吧(6) - Lisp速成
  2. Tomcat安全加固
  3. 2020双十一实时大屏_双十一实时“战报”来了,你贡献了多少?
  4. 使用JTextArea示例
  5. java的WebService实践(cxf)
  6. linux u盘新建文件夹加密,linux磁盘的加密保护以及u盘加密的方法。
  7. 解决安装XMind出现Invalid Configuration Location The configuration area at ‘C:\Users\Administrator\Applicat
  8. java中map的遍历方法_Java中Map的三种遍历方式
  9. JDBC进行事务管理
  10. .NET方法演化史 从Delegate到Lambda再到LINQ
  11. yii 标签用法(模板)
  12. Spring Boot 概述、初始化器、spring-boot-maven-plugin 插件简化部署、starter 自动配置原理
  13. 泡水十几秒仍能工作 小米手机2也能防水了
  14. 企业的病毒,要及时清理
  15. 项目系统设计和数据库设计(追光的人)
  16. 敢问路在何方 路在脚下
  17. 罗振宇2022“时间的朋友”跨年演讲全文稿(pdf)
  18. Rdlc报表纵向与横向打印问题
  19. 使用cloudflare加速你的网站隐藏你的网站IP
  20. 未转变者服务器买车指令,未转变者服务器指令大全

热门文章

  1. linux添加源地址ping,实战经验:Linux Source NAT在Ping场景下的应用
  2. #控制台大学课堂点名问题_你对大学生活的5大误解!看完我想静静......
  3. python读取日期_从文件中读取日期和数据(Python)
  4. 参考文献要不要首行缩进_参考文献格式要求(2015-2016-2)
  5. js map对象遍历_何时使用 Map 来代替变通的 JS 对象
  6. 商标45类分类表明细表_2019版注册商标分类表,商标注册45类范围明细
  7. timm 视觉库中的 create_model 函数详解
  8. 计算机一级试题论述,计算机一级考试理论题及答案要点
  9. 安装php no permision,php安装过程中的No package ‘xxx’ found问题
  10. PHP 与go 通讯,Golang和php通信