SpringMVC教程之文件(图片)上传

一、前言

Spring MVC 为文件上传提供了直接的支持,这种支持是通过即插即用的 MultipartResolver 实现的。Spring 用
Jakarta Commons FileUpload 技术实现了一个MultipartResolver 实现类:CommonsMultipartResovler
Spring MVC 上下文中默认没有装配 MultipartResovler,因此默认情况下不能处理文件的上传工作,如果想使用 Spring 的文件上传功能,需先在上下文中配置 MultipartResolver,为了让 CommonsMultipartResovler 正确工作,必须先将Commons-FileUpload及Commons-io的类包添加到类路径下。
下面我们通过相关案例演示一下单个文件上传以及多个文件上传。

二、案例

♦配置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"
	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">
	<welcome-file-list>
		<welcome-file>welcome.jsp</welcome-file>
	</welcome-file-list>

	<!-- 配置DispatcherServlet -->
	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<!-- 配置DispatcherServlet的一个初始化参数:配置SpringMVC配置文件的位置和名称 -->
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

♦配置springmvc.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:p="http://www.springframework.org/schema/p"
	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-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	<!-- 定义Controller的扫描包 -->
	<context:component-scan base-package="com.queen.springmvc" />

	<!-- 配置视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>
        
        <mvc:default-servlet-handler/>
	<mvc:annotation-driven />

	<!-- 上传文件的设置 ,maxUploadSize=-1,表示无穷大。uploadTempDir为上传的临时目录 -->  
   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   		<property name="defaultEncoding" value="UTF-8"></property>
   		<property name="maxUploadSize" value="5400000"></property>
   </bean>
</beans>

注意:<mvc:default-servlet-handler/>一定要配置进去,因为静态资源会被拦截掉,否则会报404错误
♦POM文件

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.queen.springmvc</groupId>
	<artifactId>SpringMVCTest-01</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.1.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.2.2</version>
		</dependency>
		<dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.4</version>
		</dependency>
                <dependency>
                    <groupId>jstl</groupId>
                    <artifactId>jstl</artifactId>
                    <version>1.2</version>
                </dependency>
                <dependency>
                    <groupId>taglibs</groupId>
                    <artifactId>standard</artifactId>
                    <version>1.1.2</version>
                </dependency>
	</dependencies>
	<build>
		<plugins>
			<!-- 配置Tomcat插件 -->
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<configuration>
					<port>8080</port>
					<path>/</path>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

♦单个文件上传

编写FilesUploadHandler控制器类

/**
 * @author queen
 * @since 2017-11-22
 */
@RequestMapping("/fileupload")
@Controller
public class FilesUploadHandler {

	@RequestMapping("/toFile")
	public String toFileUpload() {
		return "fileUpload";
	}

	@RequestMapping("/singlefile")
	public ModelAndView singUploadFile(@RequestParam("file") MultipartFile file,
			HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("fileUpload");

		if (file != null) {
			// 获取物理路径
			String targetDirectory = request.getSession().getServletContext()
					.getRealPath("/uploads");
			// 上传的文件名
			String tmpFileName = file.getOriginalFilename(); 
			int dot = tmpFileName.lastIndexOf('.');
			// 文件后缀名
			String ext = ""; 
			if ((dot > -1) && (dot < (tmpFileName.length() - 1))) {
				ext = tmpFileName.substring(dot + 1);
			}
			// 其他文件格式不处理
			if ("png".equalsIgnoreCase(ext) || "jpg".equalsIgnoreCase(ext)
					|| "gif".equalsIgnoreCase(ext)) {
				// 重命名上传的文件名
				String targetFileName = renameFileName(tmpFileName);
				// 保存的新文件
				File target = new File(targetDirectory, targetFileName);

				try {
					// 保存文件
					FileUtils.copyInputStreamToFile(file.getInputStream(),
							target);
				} catch (IOException e) {
					e.printStackTrace();
				}

				modelAndView.addObject("fileUrl",request.getScheme() + "://"  
			            + request.getServerName() + ":" + request.getServerPort()  
			            + request.getContextPath() + "/uploads/" + targetFileName);
			}

			return modelAndView;
		}
		
		return modelAndView;
	}

	private static String renameFileName(String fileName) {
		// 当前时间字符串
		String formatDate = new SimpleDateFormat("yyMMddHHmmss")
				.format(new Date()); 
		int random = new Random().nextInt(10000);
		// 文件后缀
		String extension = fileName.substring(fileName.lastIndexOf(".")); 

		return formatDate + random + extension;
	}
}

默认启动服务进入界面

<%@ 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>  
<title>欢迎界面</title>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
</head>  
<body>  
    <center>  
       <a href="fileupload/toFile">进入单个文件上传页面</a>  
    </center>  
</body>  
</html>  

编写文件上传界面fileUpload.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>  
<title>上传单张图片页面</title>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
</head>  
<body>  
    <center>  
        <form action="/fileupload/singlefile"  
            method="post" enctype="multipart/form-data">  
            <input type="file" name="file" />   
            <input type="submit" value="上 传" />  
        </form>  
        <h5>上传结果:</h5>  
        <img alt="暂无图片" src="${fileUrl}" />  
    </center>  
</body>  
</html>  

启动服务运行
SpringMVC教程之文件(图片)上传的照片 - 1
SpringMVC教程之文件(图片)上传的照片 - 3
点击上传
SpringMVC教程之文件(图片)上传的照片 - 5
♦多文件上传

修改FilesUploadHandler控制器类

@RequestMapping("/toManyFile")
public String toManyFile() {
	return "fileManyUpload";
}

@RequestMapping("/manyfile")
public ModelAndView manyUploadFile(
		@RequestParam("file") CommonsMultipartFile files[],
		HttpServletRequest request) {
	List<String> list = new ArrayList<String>();
	ModelAndView modelAndView = new ModelAndView("fileManyUpload");
	for (int i = 0; i < files.length; i++) {
		if (files[i] != null) {
			// 获取物理路径
			String targetDirectory = request.getSession()
					.getServletContext().getRealPath("/uploads");
			// 上传的文件名
			String tmpFileName = files[i].getOriginalFilename();
			int dot = tmpFileName.lastIndexOf('.');
			// 文件后缀名
			String ext = "";
			if ((dot > -1) && (dot < (tmpFileName.length() - 1))) {
				ext = tmpFileName.substring(dot + 1);
			}
			// 其他文件格式不处理
			if ("png".equalsIgnoreCase(ext) || "jpg".equalsIgnoreCase(ext)
					|| "gif".equalsIgnoreCase(ext)) {
				// 重命名上传的文件名
				String targetFileName = renameFileName(tmpFileName);
				// 保存的新文件
				File target = new File(targetDirectory, targetFileName);
				try {
					// 保存文件
					FileUtils.copyInputStreamToFile(
							files[i].getInputStream(), target);
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				list.add(request.getScheme() + "://"
						+ request.getServerName() + ":"
						+ request.getServerPort()
						+ request.getContextPath() + "/uploads/"
						+ targetFileName);
				modelAndView.addObject("fileList",list);
			}
		}
	}

	return modelAndView;
}

默认修改启动服务进入界面

<%@ 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>  
<title>欢迎界面</title>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
</head>  
<body>  
    <center>  
       <a href="fileupload/toFile">进入单个文件上传页面</a>  
    </center>  
    <center>  
       <a href="fileupload/toManyFile">进入多个文件上传页面</a>  
    </center>
</body>  
</html>  

编写多文件上传界面fileManyUpload.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">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<html>
<head>
<title>用户上传多张图片页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
	<center>
		<form action="/fileupload/manyfile" method="post"
			enctype="multipart/form-data">
			<input type="file" name="file" /><br /> <input type="file"
				name="file" /><br /> <input type="file" name="file" /><br /> <input
				type="submit" value="上 传" />
		</form>
		<h5>上传结果:</h5>

		<c:forEach items="${fileList}" var="imagename">
			<img alt="暂无图片" src="${imagename}" /><br />
		</c:forEach>
	</center>
</body>
</html>

启动运行
SpringMVC教程之文件(图片)上传的照片 - 7
SpringMVC教程之文件(图片)上传的照片 - 9
SpringMVC教程之文件(图片)上传的照片 - 11

至此,我们关于SpringMVC教程之文件(图片)上传介绍完毕。想要了解更多关于SpringMVC开发的教程,请参考http://www.marsitman.com/springmvc
博客地址:http://www.marsitman.com/springmvc/springmvc-upload.html
版权声明:本文为博主原创文章,允许转载,但转载必须标明出处。

 

 

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!



点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注