《SpringMVC从入门到放肆》十五、SpringMVC之上传文件
上一篇我们学习了数据分组校验,已经可以灵活的在项目中进行数据校验了,今天来学习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";
}
}
到这里文件上传就完事了。大家可以测试一下。这里我就不粘贴测试图片了。
《SpringMVC从入门到放肆》十五、SpringMVC之上传文件的更多相关文章
- 《SpringMVC从入门到放肆》五、SpringMVC配置式开发(处理器适配器)
上一篇我们大致讲解了处理器映射器的处理流程以及跟了一下源码的执行流程.今天我们来了解一下处理器适配器. 一.适配器模式 在阎宏博士的<JAVA与模式>一书中开头是这样描述适配器(Adapt ...
- Bootstrap入门(二十五)JS插件2:过渡效果
Bootstrap入门(二十五)JS插件2:过渡效果 对于简单的过渡效果,只需将 transition.js 和其它 JS 文件一起引入即可.如果你使用的是编译(或压缩)版的bootstrap.js ...
- 孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容
孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 一.打开文件后,要务必记得关闭,所以一般的写法应当 ...
- Spring+SpringMVC+MyBatis深入学习及搭建(十五)——SpringMVC注解开发(基础篇)
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7065294.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十四)--S ...
- 《SpringMVC从入门到放肆》八、SpringMVC注解式开发(基本配置)
上一篇我们结束了配置式开发,配置式开发目前在企业中用的并不是很多,大部分企业都在使用注解式开发,所以今天我们就来学习注解式开发.所谓SpringMVC注解式开发是指,处理器是基于注解的类的开发方式.对 ...
- 《SpringMVC从入门到放肆》六、SpringMVC开发Controller的方法总结
到目前为止我们已经大概学习了StringMVC的执行流程,以及详细的处理器映射器和处理器适配器的执行流程,并可以自己写一个配置方式开发的小Demo了.今天我们来总结一下实现一个Controller的几 ...
- 【Spring】SpringMVC之上传文件
这里笔者介绍利用SpringMVC上传图片的操作. 步骤 1. 引入jar文件 不仅需要导入开发SpringMVC相关的包,还需要导入 commons-fileupload-1.2.1.jar 和 ...
- 《SpringMVC从入门到放肆》十二、SpringMVC自定义类型转换器
之前的教程,我们都已经学会了如何使用Spring MVC来进行开发,掌握了基本的开发方法,返回不同类型的结果也有了一定的了解,包括返回ModelAndView.返回List.Map等等,这里就包含了传 ...
- 《SpringMVC从入门到放肆》十、SpringMVC注解式开发(复杂参数接收)
上一篇我们学习了简单的参数接收方式,以及对编码的统一处理.今天我们来接收对象参数. 一.接收对象参数 jsp页面: <%@ page language="java" impo ...
随机推荐
- Cordova 返回键切换后台
这里需要用到 cordova-plugin-backbutton 这个插件 1.安装插件,命令窗口输入(当前目录是你项目所在的目录) cordova plugin add cordova-plugin ...
- OVS 派OFPT_PORT_STATUS 流程
依据openflow合约[OFP1.0-38],当从物理端口ovs datapath 添加,改动或者删除的时候.都会先运行详细动作.然后通过ofp_port_status异步消息告知Controlle ...
- gridview分页
protected void lnkbtnFrist_Click(object sender, EventArgs e) { //首页 ; this.ReadData(); } protected v ...
- 怎么会float交换器int
最近突然想知道编译器整数浮球开关是如何实现的,现在很多信息,但遗憾的是甚至没有这方面的记录,所以我决定实现自己的简单的整数浮点转 随着float开启int为例 double转int类似 在做强转之前 ...
- python 两个链表的第一个公共结点
题目描述 输入两个链表,找出它们的第一个公共结点. 看到这道题的时候,很多人的第一反应就是采用蛮力的方法:在第一个链表上顺序遍历每个节点,每遍历到一个节点的时候,在第二个链表上顺序遍历每个节点.如 ...
- Python 函数调用性能记录
之前用 JS 写项目的时候,项目组用的组件模式,一直感觉很不错.最近用 Python 做新项目,项目结构也延续了组件模式.一直没有对函数调用的性能作了解,今天突发奇想测试了一下,写了一些测试代码 首先 ...
- OpenGL(五) 三维变换之模型视图矩阵
计算机三维图形学中,一个基本的任务是如何描述三维空间中一个物体位置的变化,也就是如何 描述物体的运动.通常情况下,物体位置的变化包含三个基本的变化:平移.旋转和缩放,物体的运动也可以用这三个基本的运动 ...
- linux nano 命令
linux nano一linux像pico文本编辑软件,功能少.但是,基本能满足要求
- 基于Linux C的socketEthereal程序和Package分析 (一个)
执行测试平台:CentOS 6.5发行版,内核版本号3.11 1. Linux抓包源程序 在OSI七层模型中.网卡工作在物理层和数据链路层的MAC子层. 进行网络通信时.源主机通过socket( ...
- eXtremeDB -- the shared memory 80error
The customers got the shared memory 80error on AIX environment; utility truss is used to track the d ...