Spring MVC文件上传教程 commons-io/commons-uploadfile

Spring MVC文件上传教程 commons-io/commons-uploadfile

用到的依赖jar包:

commons-fileupload 1.3.1
commons-io 2.4

 

基于 Spring MVC来实现文件的上传功能,这里主要是实现两个功能:1、上传单个文件并将其移动到对应的上传目录;2、一次上传多个文件并将它们存储在指定文件夹下,接下来我们一步步地实现。

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>gugua4</groupId>
  <artifactId>gugua17</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>gugua17 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  
  <properties>
  	<spring.version>4.3.5.RELEASE</spring.version>
  </properties>
  
  
  <dependencies>
  
  
     <!-- spring模块库 -->
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-beans</artifactId>
    	<version>${spring.version}</version>
    </dependency> 
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-web</artifactId>
    	<version>${spring.version}</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-webmvc</artifactId>
    	<version>${spring.version}</version>
    </dependency>  
	<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
	<!-- transaction事务 -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-tx</artifactId>
	    <version>${spring.version}</version>
	</dependency>
	
	
	
	<!-- Servlet dependencies -->
    <!-- servlet(HttpServletRequest,HttpServletResponse) -->	
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>javax.servlet-api</artifactId>
		<version>3.1.0</version>
	</dependency>
	
	<!-- Jstl for jsp page -->
	<!-- https://mvnrepository.com/artifact/jstl/jstl -->
	<dependency>
	    <groupId>jstl</groupId>
	    <artifactId>jstl</artifactId>
	    <version>1.2</version>
	</dependency>
	
	<!-- JSP API -->
    <!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
    <dependency>
         <groupId>javax.servlet.jsp</groupId>
         <artifactId>jsp-api</artifactId>
         <version>2.2</version>
         <scope>provided</scope>
     </dependency>
	
    
    <!-- 文件上传 -->
	<!-- Apache Commons FileUpload -->
	<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
	<dependency>
	    <groupId>commons-fileupload</groupId>
	    <artifactId>commons-fileupload</artifactId>
	    <version>1.3.1</version>
	</dependency>
	 <!-- Apache Commons IO -->
     <!-- http://mvnrepository.com/artifact/commons-io/commons-io -->
     <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    
    
  </dependencies>
  
  
  <build>
    <finalName>gugua17</finalName>
    <pluginManagement>
    	<plugins>
    		<plugin>
    			<groupId>org.apache.maven.plugins</groupId>
    			<artifactId>maven-war-plugin</artifactId>
    			<version>2.6</version>
    		</plugin>
    	</plugins>
    </pluginManagement>
  </build>
  
</project>

  

web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>  		
  		org.springframework.web.servlet.DispatcherServlet
  	</servlet-class>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
  
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
  
  <listener>
  	<listener-class>
  		org.springframework.web.context.ContextLoaderListener
  	</listener-class>
  </listener>
  
</web-app>

  

spring-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
					http://www.springframework.org/schema/beans/spring-beans.xsd
					http://www.springframework.org/schema/mvc
					http://www.springframework.org/schema/mvc/spring-mvc.xsd
					http://www.springframework.org/schema/context
					http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 引入包  -->
<context:component-scan base-package="springmvc"/>

<!-- 自动装配 -->
<context:annotation-config/>

<!-- 视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix">
		<value>/WEB-INF/views/</value>
	</property>
	<property name="suffix">
		<value>.jsp</value>
	</property>
</bean>

<!-- 上传文件配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!-- Maximum file size: 1MB -->
    <!-- 1MB = 125000 Byte -->
	<property name="maxUploadSize" value="125000"/>
</bean>

</beans>

  

applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
					http://www.springframework.org/schema/beans/spring-beans.xsd
					http://www.springframework.org/schema/mvc
					http://www.springframework.org/schema/mvc/spring-mvc.xsd
					http://www.springframework.org/schema/context
					http://www.springframework.org/schema/context/spring-context.xsd">




</beans>

  

jsp:

uploadOneFile.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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>upload one file</title>
</head>
<body>

<h3>upload one file</h3>
<form method="post" action="do" enctype="multipart/form-data">
	upload to file:<input type="file" name="file"><br>
	<input type="submit" value="upload">
</form>


</body>
</html>

  

uploadMultiFile.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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>upload multi file</title>
</head>
<body>


<h3>upload multi file</h3>
<form method="post" action="do" enctype="multipart/form-data">
	upload to file(1):<input type="file" name="file"><br>
	upload to file(2):<input type="file" name="file"><br>
	upload to file(3):<input type="file" name="file"><br>
	upload to file(4):<input type="file" name="file"><br>
	upload to file(5):<input type="file" name="file"><br>
	<input type="submit" value="upload">
</form>


</body>
</html>

  

uploadResult.xml

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>upload result</title>
</head>
<body>

<h3>upload files:</h3>
<c:forEach items="${uploadFiles}" var="file">
	-${file}<br>
</c:forEach>



</body>
</html>

  

controller

MultipartUploadController.java

package springmvc.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;

@Controller
public class MultipartUploadController {

	
	@RequestMapping(value="/upload/one", method=RequestMethod.GET)
	public String uploadOneFile()
	{		
		return "uploadOneFile";
	}
	
	
	@RequestMapping(value="/upload/multi", method=RequestMethod.GET)
	public String uploadMultiFile()
	{
		return "uploadMultiFile";		
	}
	
	
	@RequestMapping(value="/upload/do", method=RequestMethod.POST)
	public String uploadDo(HttpServletRequest request, Model model, @RequestParam("file") MultipartFile[] files)
	{
		//获取目录/创建路径
		String uploadRootPath = request.getServletContext().getRealPath("upload");
		System.out.println(uploadRootPath);
		//获取路径
		File uploadRootDir = new File(uploadRootPath);
		if(!uploadRootDir.exists())
		{
			uploadRootDir.mkdirs();
		}
		
		//用来存放上传后的路径地址的变量
		List<File> uploadFiles = new ArrayList<File>();
		for(int i = 0; i < files.length; i++)
		{
			MultipartFile file = files[i];
			
			//原文件名
			String name = file.getOriginalFilename();
			System.out.print(name);

			
			if(name != null && name.length() > 0)
			{
				try {
					
					//获取文件字节流
					byte[] bytes = file.getBytes();
					
					//新文件路径
					File serverFile = new File( uploadRootDir.getAbsolutePath() + File.separator + name );							
					
					//将文件字节流输出到刚创建的文件上
					BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream( serverFile ) );
					stream.write(bytes);
					stream.close();
					
					//将文件路径添加到uploadFiles中
					uploadFiles.add( serverFile );
					System.out.println( serverFile );
					
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					System.out.println("error to file:" + name);
				}
			}	
			
		}
		model.addAttribute("uploadFiles", uploadFiles);
		return "uploadResult";
		
	}
	
}

  

 

 

 

 

 

 

 

 

 

  

 

posted @ 2018-06-14 17:11  穆晟铭  阅读(956)  评论(0编辑  收藏