《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 ...
随机推荐
- ASP.Net请求小周期
另一篇另篇2 ASP.NET请求处理全过程 一个ASP.NET请求过程中,从浏览器中发出一个Web请求 到 这个请求被响应并显示在浏览器中的过程中究竟会发生哪些不同的事件,当我们进入这个事件之旅时,我 ...
- Windows SublimeText内使用NDK编译Android so(不用cygwin)
測试环境: sublime text version 2.0.2, build 2221 和 sublime text stable channel, build 3065 (version3) Wi ...
- Tagging Physical Resources in a Cloud Computing Environment
A cloud system may create physical resource tags to store relationships between cloud computing offe ...
- 深入WPF中的图像画刷(ImageBrush)之1——ImageBrush使用举例
原文:深入WPF中的图像画刷(ImageBrush)之1--ImageBrush使用举例 昨天我在<简述WPF中的画刷(Brush) >中简要介绍了WPF中的画刷的使用.现在接着深入研究 ...
- 如何使用GDI绘制半透明矩形
/*使用GDI绘制半透明矩形*/ void CDirectXDraw::DrawHalfOpacityRect(HDC hdc,CRect rect) { CDC dc; dc.Attach(hdc) ...
- CefSharp For WPF基本使用
原文:CefSharp For WPF基本使用 Nuget引用 CefSharp.Wpf CefSharp.Common cef.redist.x64 cef.redist.x86 直接搜索安装Cef ...
- python_matplotlib cannot import name _thread on mac
最后的2行错误信息是 from six.moves import _thread ImportError: cannot import name _thread 1 2 发现是six出现了问题,用pi ...
- opengl实现直线扫描算法和区域填充算法
总体介绍 1. 使用线性扫描算法画一条线,线性离散点 2. 利用区域填充算法画多边形区域,区域离散的点 开发环境VS2012+OpenGL 开发平台 Intel core i5,Intel H ...
- iOS NSString追加字符串的方法
第一种: NSArray *array = [NSArray arrayWithObjects:@"Hello",@" ",@"world" ...
- 把BitmapSource图片数据保存到文件
实现函数: /// <summary> /// 保存图片到文件 /// </summary> /// <param name="image">图 ...