基于
spring 3.0 mvc框架的文件上传实现
需要引入
springmvc 相关
jar包、
apache.commons.io.jar、
apache.commons.fileupload.jar
1、首先在springmvc-servlet.xml配置文件中加上配置:
<!-- 处理文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="gbk" /><!-- 默认编码 (ISO-8859-1) -->
<property name="maxInMemorySize" value="10240" /><!-- 最大内存大小 (10240)-->
<property name="maxUploadSize" value="-1" /><!-- 最大文件大小,-1为无限止(-1) -->
</bean>
2、编写文件上传的upload.jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>测试springmvc中上传的实现</title>
</head>
<body>
<form action="./upload" method="post" enctype="multipart/form-data"><!-- 一定要配置enctype属性,否则会出错 -->
<input type="text" name="name" />
<input type="file" name="file" />
<input type="submit" />
</form>
</body>
</html>
3、编写处理文件上传的Controller类:这里上传的文件会保存在项目下的文件夹upload中
@Controller
@RequestMapping("/user")
public class UserController implements ServletContextAware{
//实现ServletContextAware接口是为了注入web上下文servletContext
private ServletContext servletContext;
@Override
public void setServletContext(ServletContext context) {
this.servletContext=context;
}
//文件上传
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String fileUpload(String name,@RequestParam("file") CommonsMultipartFile file){
if(!file.isEmpty()){
String path = this.servletContext.getRealPath("/upload/");//在web上下文中获取upload这个文件夹的路径,这个upload文件夹须在项目中存在
System.out.println(path);
String fileName=file.getOriginalFilename();
String fileType=fileName.substring(fileName.lastIndexOf("."));
System.out.println(fileType);
File file2=new File(path,new Date().getTime()+fileType);//新建一个文件,以时间戳为文件名字
try{
file.getFileItem().write(file2);//将上传的文件写入新建的文件中
}catch(Exception e){
e.printStackTrace();
}
return "redirect:success.jsp";//使用重定向到success.jsp页面
}else{
return "redirect:fail.jsp";//使用重定向到fail.jsp页面
}
}
}
这里的succuess.jsp和fail.jsp读者自行编写,这里不会影响功能。