上一篇我们学习了数据分组校验,已经可以灵活的在项目中进行数据校验了,今天来学习SpringMVC的上传文件功能。相对来说SpringMVC的上传功能,还是比较简单的。
一、添加依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
二、修改applicationContext.xml配置文件
要想实现上传功能,必须要配置一个解析器,如下:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize"><!-- 最大上传文件大小 100M -->
<value>104857600</value>
</property>
<property name="maxInMemorySize"><!-- 最大上传缓存大小 4k -->
<value>4096</value>
</property>
</bean>
上述代码设置了支持最大的上传大小为100M,如果文件超出大小,则会报错,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException,而这个时候,代码还没有执行到我们的Controller中,所以最好再配置一个异常处理解析器。如下:
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到XXX页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">跳转页面URL</prop>
</props>
</property>
</bean>
到这里我们需要配置的信息就完事了,接下来就是具体的开发了,是不是好期待呀???
三、编写上传页面
<%@ 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>上传文件</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">
上传文件:<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
页面比较简陋,大家不要介意,这里主要讲解功能。
四、编写上传Controller
package cn.itechyou.upload.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
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;
@Controller
public class TestUploadController {
/**
* 单文件上传
* @param file
* @param request
* @return
*/
@RequestMapping(value = "/upload.do")
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
if (!file.isEmpty()) {
String type = file.getOriginalFilename().substring(
file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
String path = request.getSession().getServletContext()
.getRealPath("/upload/" + filename);// 存放位置
File destFile = new File(path);
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:ok.jsp";
} else {
return "redirect:error.jsp";
}
}
/**
* 多文件上传
* @param request
* @param files
* @return
*/
@RequestMapping(value = "uploads", method = RequestMethod.POST)
public String uploads(HttpServletRequest request, @RequestParam("files") MultipartFile[] files){
StringBuilder sb = new StringBuilder();
if(files != null && files.length > 0){
for (MultipartFile file : files) {
if (!file.isEmpty()) {
String type = file.getOriginalFilename().substring(
file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
String path = request.getSession().getServletContext()
.getRealPath("/upload/" + filename);// 存放位置
File destFile = new File(path);
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
sb.append("1");
} catch (IOException e) {
sb.append("0");
e.printStackTrace();
}
} else {
sb.append("0");
}
}
}
//这里做个判断,如果上传文件中有上传失败的,则返回错误页面
if(sb.toString().contains("0")){
return "redirect:error.jsp";
}
return "redirect:ok.jsp";
}
}
到这里文件上传就完事了。大家可以测试一下。这里我就不粘贴测试图片了。