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

SpringMVC上传文件的三种方式

程序员文章站 2022-05-28 17:01:04
...

  项目结构如下所示:

SpringMVC上传文件的三种方式
            
    
    博客分类: spring spring上传 

  upload.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>fileUpload</title>
	</head>
	<body>
		<form name="serForm" action="/SpringMVC/upload/fileUpload" method="post"  enctype="multipart/form-data">
			<h1>file stream upload:</h1>
			<input type="file" name="file">
			<input type="submit" value="upload"/>
		</form>
		 
		<form name="Form2" action="/SpringMVC/upload/fileUpload2" method="post"  enctype="multipart/form-data">
			<h1>multipart file.transfer upload:</h1>
			<input type="file" name="file">
			<input type="submit" value="upload"/>
		</form>
		 
		<form name="Form2" action="/SpringMVC/upload/springUpload" method="post"  enctype="multipart/form-data">
			<h1>spring mvc upload:</h1>
			<input type="file" name="file">
			<input type="submit" value="upload"/>
		</form>
	</body>
</html>

  UploadController.java

package com.bijian.study.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
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;

@Controller
@RequestMapping("/upload")
public class UploadController {

	/*
	 * 通过流的方式上传文件
	 * 
	 * @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
	 */
	@RequestMapping("/fileUpload")
	public String fileUpload(@RequestParam("file") CommonsMultipartFile file)
			throws IOException {

		// 用来检测程序运行时间
		long startTime = System.currentTimeMillis();
		System.out.println("fileName:" + file.getOriginalFilename());

		try {
			// 获取输出流
			OutputStream os = new FileOutputStream("E:/upload/" + new Date().getTime()
					+ file.getOriginalFilename());
			// 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
			InputStream is = file.getInputStream();
			int temp;
			// 一个一个字节的读取并写入
			while ((temp = is.read()) != (-1)) {
				os.write(temp);
			}
			os.flush();
			os.close();
			is.close();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		long endTime = System.currentTimeMillis();
		System.out.println("方法一的运行时间:" + String.valueOf(endTime - startTime) + "ms");
		return "/success";
	}

	/*
	 * 采用file.Transto 来保存上传的文件
	 */
	@RequestMapping("fileUpload2")
	public String fileUpload2(@RequestParam("file") CommonsMultipartFile file)
			throws IOException {
		long startTime = System.currentTimeMillis();
		System.out.println("fileName:" + file.getOriginalFilename());
		String path = "E:/upload/" + new Date().getTime() + file.getOriginalFilename();

		File newFile = new File(path);
		// 通过CommonsMultipartFile的方法直接写文件(注意这个时候)
		file.transferTo(newFile);
		long endTime = System.currentTimeMillis();
		System.out.println("方法二的运行时间:" + String.valueOf(endTime - startTime) + "ms");
		return "/success";
	}

	/*
	 * 采用spring提供的上传文件的方法
	 */
	@RequestMapping("springUpload")
	public String springUpload(HttpServletRequest request)
			throws IllegalStateException, IOException {
		long startTime = System.currentTimeMillis();
		// 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();

			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next()
						.toString());
				if (file != null) {
					String path = "E:/upload/springUpload" + file.getOriginalFilename();
					// 上传
					file.transferTo(new File(path));
				}

			}

		}
		long endTime = System.currentTimeMillis();
		System.out.println("方法三的运行时间:" + String.valueOf(endTime - startTime) + "ms");
		return "/success";
	}
}

  hbatis-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<!-- 注册RequestMappingHandlerMapping, RequestMappingHandlerAdapter和ExceptionHandlerExceptionResolver以提供对@RequestMapping,@ExceptionHandler等注解的支持 -->
	<mvc:annotation-driven />

	<!-- 扫描控制器包下有特定注解的类,并实例化和依赖注入 -->
	<context:component-scan base-package="com.bijian.study.controller" />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
	
	<!-- 多部分文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     	<property name="maxUploadSize" value="104857600" />
     	<property name="maxInMemorySize" value="4096" />
     	<property name="defaultEncoding" value="UTF-8"></property>
	</bean>
</beans>

  web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
   
	<display-name>SpringMVC</display-name>
	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext.xml</param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
		<!-- 监听容器事件,初始化和关闭Web应用上下文并调用ContextCleanupListener清理资源 -->
	</listener>
	<listener>
		<listener-class>org.springframework.web.context.ContextCleanupListener</listener-class>
		<!-- Web应用关闭时,清理ServletContext中spring相关的可销毁资源 -->
	</listener>

	<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>
		</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>
	</filter-mapping>
	
	<servlet>
	  <servlet-name>hbatis</servlet-name>
	  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	  <!--<init-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>/WEB-INF/hbatis-servlet.xml</param-value>
	  </init-param>-->
	  <!-- 未配置时,SpringMVC会到WEB-INF目录下找${servlet-name}-servlet.xml -->
	  <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
	  <servlet-name>hbatis</servlet-name>
    <url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>  

  打开http://localhost:8080/SpringMVC/upload.jsp上传页面,如下所示:

SpringMVC上传文件的三种方式
            
    
    博客分类: spring spring上传 
  我们看看测试上传的时间,第一次我用一个4M的文件,运行结果如下:

fileName:test.rar
方法一的运行时间:14712ms
fileName:test.rar
方法二的运行时间:5ms
方法三的运行时间:4ms

  第二次:我用一个50M的文件

方式一进度很慢,估计得要个5分钟
方法二的运行时间:67ms
方法三的运行时间:80ms

  从测试结果我们可以看到:用springMVC自带的上传文件的方法要快的多!

  对于测试二的结果:可能是方法三得挨个搜索,所以要慢点。不过一般情况下我们是方法三,因为他能提供给我们更多的方法。

 

PS:工程里需引入commons-fileupload和commons-io这两个jar包,在这里我用的是commons-fileupload-1.3.jar和commons-io-2.4.jar。

 

文章来源:https://www.cnblogs.com/fjsnail/p/3491033.html

  • SpringMVC上传文件的三种方式
            
    
    博客分类: spring spring上传 
  • 大小: 11.7 KB
  • SpringMVC上传文件的三种方式
            
    
    博客分类: spring spring上传 
  • 大小: 18.8 KB
相关标签: spring 上传

上一篇: 数组拆分

下一篇: java反射