关于文件的上传,之前写过2篇文章,基于Struts2框架,下面给出文章链接:

关于Struts2的文件上传》:http://www.cnblogs.com/lichenwei/p/3927964.html

关于Struts2的多文件上传》:http://www.cnblogs.com/lichenwei/p/3928200.html

其实文件上传的原理都是一样的,基于SpringMVC的文件上传实现要比Struts2要来得简单许多。

好了,废话不多说,直接切入主题吧,关于上传原理不了解的朋友,可以轻戳上面2篇文章的链接。

1、万变不离其宗,要实现文件的上传需要对应的JAR包:

1、commons-fileupload-1.2.2.jar

2、commons-io-2.0.1.jar

2、要实现SpringMVC的文件上传,需要配置一下文件:

     <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="-1" />
</bean> <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- 该异常是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">跳转XXX页面</prop>
</props>
</property>
</bean>

3、上传页面

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%> <!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="<%=basePath%>upload.do" method="post"
enctype="multipart/form-data">
<input type="hidden" name="tuzi" value="tuzi">
上传文件:<input type="file" name="uploadfile">
<input type="submit" value="上传">
</form>
</body>
</html>

4、文件处理类:

 package lcw.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.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile; /**
*
* 文件上传处理类
*
*/
@Controller
public class FileController { //单文件上传
@RequestMapping(value = "/upload.do")
public String queryFileData(
@RequestParam("uploadfile") CommonsMultipartFile file,
HttpServletRequest request) {
// MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
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()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
FileUtils
.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:upload_ok.jsp";
} else {
return "redirect:upload_error.jsp";
}
}
}

5、看一下实现效果图:

6、再来看下关于多文件上传,其实原理还是一样,只不过是把CommonsMultipartFile类对象换成一个数组,然后用一个for循环去遍历这个数组,并分别存入。

 package lcw.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.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile; /**
*
* 文件上传处理类
*
*/
@Controller
public class FileController { //单文件上传
@RequestMapping(value = "/upload.do")
public String queryFileData(
@RequestParam("uploadfile") CommonsMultipartFile file,
HttpServletRequest request) {
// MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
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()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
FileUtils
.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:upload_ok.jsp";
} else {
return "redirect:upload_error.jsp";
}
} //多文件上传
@RequestMapping(value = "/uploads.do")
public String queryFileDatas(
@RequestParam("uploadfile") CommonsMultipartFile[] files,
HttpServletRequest request) {
if (files != null) {
for (int i = 0; i < files.length; i++) {
String type = files[i].getOriginalFilename().substring(
files[i].getOriginalFilename().indexOf("."));// 取文件格式后缀名
String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
String path = request.getSession().getServletContext()
.getRealPath("/upload/" + filename);// 存放位置
File destFile = new File(path);
try {
FileUtils.copyInputStreamToFile(files[i].getInputStream(),
destFile);// 复制临时文件到指定目录下
} catch (IOException e) {
e.printStackTrace();
}
}
return "redirect:upload_ok.jsp";
} else {
return "redirect:upload_error.jsp";
} } }

7、看下效果图:

作者:Balla_兔子
出处:http://www.cnblogs.com/lichenwei/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!旁边有“推荐”二字,你就顺手把它点了吧,相得准,我分文不收;相不准,你也好回来找我!

最新文章

  1. Axure RP 7.0注册码
  2. hdu 5596 GTW likes gt
  3. php 过滤英文标点符号 过滤中文标点符号
  4. 屠蛟之路_蛟灵岛战役(下)_SeventhDay
  5. Mysql数据库操作系统及配置参数优化
  6. TYVJ P1082 找朋友 Label:字符串
  7. .net下连接数据库
  8. labview 中的一些简写全称
  9. iOS 小知识 - #if , #ifdef , #ifndef.
  10. Struts2中的链接标签 &lt;s:url&gt;和&lt;s:a&gt;---在action中获取jsp表单提交的参数(转)
  11. nginx虚拟配置
  12. QT学习笔记—1
  13. 201521123005 《Java程序设计》 第十周学习总结
  14. DevOps之三 Git的安装与配置
  15. (70)Wangdao.com第十一天_JavaScript 日期对象 Date
  16. thymeleaf中js跳转到另外一个页面
  17. 类和JSP关系
  18. Window 包管理工具: chocolatey
  19. git中出现remote: HTTP Basic: Access denied
  20. ADO.NET链接数据库封装方法

热门文章

  1. IOS 地图移动中心点获取
  2. java程序设计
  3. IBM ILOG JViews Charts 产品及功能介绍
  4. Android 避免APP启动闪黑屏(Theme和Style)
  5. C#中的Partial
  6. Android ——利用OnDraw实现自定义View(转)
  7. orderBy 传入属性的字符串
  8. Nginx+php (十六)
  9. Extjs4 页面加载先白屏后显示的bug解决
  10. nginx 4层tcp代理获取真实ip