效果:
需要的资源:
commons-fileupload-1.3.1.jar,commons-io-1.3.2.jar
步骤:
1:搭建SSM框架:
2:在配置文件springconfig.xml中添加配置
<!-- 定义文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8" />
<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880" />
<property name="maxInMemorySize" value="4096" />
</bean>
3:编写上传jsp文件:upload.jsp
<%@ 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>
<h1>文件上传实例</h1>
<form enctype="multipart/form-data" method="post" action="${pageContext.request.contextPath}/upload.action" >
<a>选择一个文件:</a>
<input type="file" name="file" /><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>
4:编辑控制器
/**
* 文件上传功能
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value="/upload",method=RequestMethod.POST)
@ResponseBody
public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
String fileMsg = UploadFileMsg(request);
System.out.println("fileMsg:"+fileMsg);
String path = request.getSession().getServletContext().getRealPath("upload");//目录
String fileName = file.getOriginalFilename();//文件名
System.out.println("path:"+path);
System.out.println("fileName:"+fileName);
File dir = new File(path,fileName);
if(!dir.exists()){//如果目录不存在,则创建
dir.mkdirs();
}
//MultipartFile自带的解析方法
file.transferTo(dir);//下载文件
System.out.println("ok");
return "success";
}
5:运行,成功的话页面信息如下,且对应目录下有文件信息