上一篇我们学习了数据分组校验,已经可以灵活的在项目中进行数据校验了,今天来学习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";
}
}

到这里文件上传就完事了。大家可以测试一下。这里我就不粘贴测试图片了。

最新文章

  1. 活用UML-软件设计高手(深圳 2014年4月26-27日)
  2. 为什么operator&gt;&gt;(istream&amp;, string&amp;)能够安全地读入长度未知的字符串?
  3. Kindle支持哪些格式
  4. Window 对象详解 转自 http://blog.csdn.net/jcx5083761/article/details/41243697
  5. [Tool] Windows 8.1安装SQL Server
  6. 12.python笔记之mysqldb模块
  7. plupload+struts2实现文件上传下载
  8. HDU 3259 Wormholes
  9. 在Dubbo中开发REST风格的远程调用(RESTful Remoting)
  10. java web 一次请求从开始到响应结束的过程
  11. Android开发详解之onTouch和onClick详解
  12. [Java] Java IO Files
  13. 众数问题(为什么只能输入一组数据,不能输入m组数据)
  14. block 解析 - 成员变量
  15. Java设计模式(三)原型模型 适配器型号
  16. Vultr VPS测试IP $5/月KVM-512MB/15G SSD/1T
  17. DEV下拉框LookUpEdit使用技巧
  18. JS组件系列——基于Bootstrap Ace模板的菜单Tab页效果优化
  19. 通过本质看现象:关于Integer受内部初始化赋值范围限制而出现的有趣现象
  20. Metasploit渗透测试实际应用

热门文章

  1. Formview单文档或对话框项目接受不到按键消息的解决办法
  2. Disk array controller and information processing apparatus
  3. java学习笔记(6)——序列化
  4. Method of packet transmission from node and content owner in content-centric networking
  5. c语言bit倒置最好的算法-离msb-lsb至lsb-msb
  6. requireJS简单的学习门户网站
  7. Leetcode dfs Combination Sum
  8. react项目实践——(1)使用webpack创建项目
  9. abp框架(aspnetboilerplate)设置前端报错显示
  10. C# 操作XML文档 使用XmlDocument类方法