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。所有的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进行多文件的效率显然要比字符流写入方式效率上要高得多。
springMVC两种方式实现多文件上传及效率比较的更多相关文章
- Django学习——ajax发送其他请求、上传文件(ajax和form两种方式)、ajax上传json格式、 Django内置序列化(了解)、分页器的使用
1 ajax发送其他请求 1 写在form表单 submit和button会触发提交 <form action=""> </form> 注释 2 使用inp ...
- ajax方式提交带文件上传的表单,上传后不跳转
ajax方式提交带文件上传的表单 一般的表单都是通过ajax方式提交,所以碰到带文件上传的表单就比较麻烦.基本原理就是在页面增加一个隐藏iframe,然后通过ajax提交除文件之外的表单数据,在表单数 ...
- 十三:SpringBoot-基于Yml配置方式,实现文件上传逻辑
SpringBoot-基于Yml配置方式,实现文件上传逻辑 1.文件上传 2.搭建文件上传界面 2.1 引入页面模板Jar包 2.2 编写简单的上传页面 2.3 配置页面入口 3.SpringBoot ...
- 04springMVC结构,mvc模式,spring-mvc流程,spring-mvc的第一个例子,三种handlerMapping,几种控制器,springmvc基于注解的开发,文件上传,拦截器,s
1. Spring-mvc介绍 1.1市面上流行的框架 Struts2(比较多) Springmvc(比较多而且属于上升的趋势) Struts1(即将被淘汰) 其他 1.2 spring-mv ...
- 用SpringMVC实现的上传下载方式二(多文件上传)
参考来源: http://blog.csdn.net/qq_32953079/article/details/52290208 1.导入相关jar包 commons-fileupload.j ...
- JavaEE开发之SpringMVC中的自定义消息转换器与文件上传
上篇博客我们详细的聊了<JavaEE开发之SpringMVC中的静态资源映射及服务器推送技术>,本篇博客依然是JavaEE开发中的内容,我们就来聊一下SpringMVC中的自定义消息转发器 ...
- springMVC+spring+mybatis整合(包括文件上传和下载)
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncod ...
- TP框架配合jquery进行3种方式的多图片上传
用的TP5.1框架+jquery 一 使用form表单方式进行多图片上传 html代码: <form action="../admin/admin/cs" enctype=& ...
- SpringBoot2.0 基础案例(14):基于Yml配置方式,实现文件上传逻辑
本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.文件上传 文件上传是项目开发中一个很常用的功能,常见的如头像上 ...
随机推荐
- 前端程序员的蜕变——JS的 event 对象属性、使用实例、兼容性处理(极大提高代码效率、减少代码量)
下面讨论一下 js 中的 Event 对象,主要从以下三个方面详细的描述(点击标题可跳转到对应部分): 1.什么是event 2.怎么用event,用他该注意什么,几个简单实际应用 3.event在不 ...
- 【面经】腾讯和YY实习生面试总结
[前言] 之前的四月份和五月份各面试了腾讯和YY的暑假实习,腾讯的失败了,YY的成功了.面试中我总会遇到自己不懂的,所幸的是不懂的越来越少,自己也一步一脚印得攻克自己不懂的.此时六月份的我再回顾起来, ...
- 有关LinkedList常用方法的源码解析
上文里解析了有关ArrayList中的几个常用方法的源码——<有关ArrayList常用方法的源码解析>,本文将对LinkedList的常用方法做简要解析. LinkedList是基于链表 ...
- validateform正则表达式 datatype验证数字
正则表达式验证正数负数 浮点数/^\-?[0-9]+(.[0-9]+)?$/ datatype="/^\-?[0-9]+(.[0-9]+)?$/"
- linux下安装apache最常见的报错解决
报错如下: Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, ...
- css清除浮动float
css清除浮动float 1.分析HTML代码 <div class="outer"> <div class="div1">1</ ...
- html标签及用法小结
html标签小结 这几天学习了html,才发现各种标签真是多的不行,所以打算把一些个常用的标签拿出来稍微说一下. *** 常用基础标签 大体上分了三类: 带有语义的标签 带有一定样式的标签(此类标签页 ...
- 解决SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT 'OpenRowset/OpenDatasource' 的访问
根据需要进行asp.net的数据导入导出,结果报以下错: mark-1: [报错]SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT ...
- Android 任何位置的可移动悬浮窗
刚好要做这块的东西,所以网上翻了下资料,百度出来的基本上都是:默认起始位置左上角,还不能改动,一改动起始位置,第二次拖动就不正常了~~ 下面直接附上任意位置可拖动的源码(由于是demo写的比较乱): ...
- ArchSummit全球架构师峰会2017年深圳站 漫谈
自去年6月跳槽到某CDN厂,从偏向移动端开发又回到了专注后端,关于做一个移动应用独立开发者的计划暂时搁置,但是如马云所讲: "梦想还是要有的,万一实现了呢".去年下半年辛苦加班加点 ...