上一篇我们学习了数据分组校验,已经可以灵活的在项目中进行数据校验了,今天来学习SpringMVC的上传文件功能。相对来说SpringMVC的上传功能,还是比较简单的。
一、添加依赖
1<dependency>
2 <groupId>commons-io</groupId>
3 <artifactId>commons-io</artifactId>
4 <version>2.4</version>
5</dependency>
6<dependency>
7 <groupId>commons-fileupload</groupId>
8 <artifactId>commons-fileupload</artifactId>
9 <version>1.3.1</version>
10</dependency>
二、修改applicationContext.xml配置文件
要想实现上传功能,必须要配置一个解析器,如下:
1<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
2 <property name="maxUploadSize"><!-- 最大上传文件大小 100M -->
3 <value>104857600</value>
4 </property>
5 <property name="maxInMemorySize"><!-- 最大上传缓存大小 4k -->
6 <value>4096</value>
7 </property>
8</bean>
上述代码设置了支持最大的上传大小为100M,如果文件超出大小,则会报错,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException,而这个时候,代码还没有执行到我们的Controller中,所以最好再配置一个异常处理解析器。如下:
1<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
2<bean id="exceptionResolver"
3 class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
4 <property name="exceptionMappings">
5 <props>
6 <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到XXX页面 -->
7 <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">跳转页面URL</prop>
8 </props>
9 </property>
10</bean>
到这里我们需要配置的信息就完事了,接下来就是具体的开发了,是不是好期待呀???
三、编写上传页面
1<%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7<title>上传文件</title>
8</head>
9<body>
10 <form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">
11 上传文件:<input type="file" name="file">
12 <input type="submit" value="上传">
13 </form>
14</body>
15</html>
页面比较简陋,大家不要介意,这里主要讲解功能。
四、编写上传Controller
1package cn.itechyou.upload.controller;
2
3import java.io.File;
4import java.io.IOException;
5
6import javax.servlet.http.HttpServletRequest;
7
8import org.apache.commons.io.FileUtils;
9import org.springframework.stereotype.Controller;
10import org.springframework.web.bind.annotation.RequestMapping;
11import org.springframework.web.bind.annotation.RequestMethod;
12import org.springframework.web.bind.annotation.RequestParam;
13import org.springframework.web.multipart.MultipartFile;
14
15@Controller
16public class UploadController {
17 /**
18 * 单文件上传
19 * @param file
20 * @param request
21 * @return
22 */
23 @RequestMapping(value = "/upload.do")
24 public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
25 if (!file.isEmpty()) {
26 String type = file.getOriginalFilename().substring(
27 file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
28 String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
29 String path = request.getSession().getServletContext()
30 .getRealPath("/upload/" + filename);// 存放位置
31 File destFile = new File(path);
32 try {
33 FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
34 } catch (IOException e) {
35 e.printStackTrace();
36 }
37 return "redirect:ok.jsp";
38 } else {
39 return "redirect:error.jsp";
40 }
41 }
42
43 /**
44 * 多文件上传
45 * @param request
46 * @param files
47 * @return
48 */
49 @RequestMapping(value = "uploads", method = RequestMethod.POST)
50 public String uploads(HttpServletRequest request, @RequestParam("files") MultipartFile[] files){
51 StringBuilder sb = new StringBuilder();
52 if(files != null && files.length > 0){
53 for (MultipartFile file : files) {
54 if (!file.isEmpty()) {
55 String type = file.getOriginalFilename().substring(
56 file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
57 String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
58 String path = request.getSession().getServletContext()
59 .getRealPath("/upload/" + filename);// 存放位置
60 File destFile = new File(path);
61 try {
62 FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
63 sb.append("1");
64 } catch (IOException e) {
65 sb.append("0");
66 e.printStackTrace();
67 }
68 } else {
69 sb.append("0");
70 }
71 }
72 }
73 //这里做个判断,如果上传文件中有上传失败的,则返回错误页面
74 if(sb.toString().contains("0")){
75 return "redirect:error.jsp";
76 }
77 return "redirect:ok.jsp";
78 }
79}
到这里文件上传就完事了。大家可以测试一下。这里我就不粘贴测试图片了。