一、前台页面
<form name="uploadFile2" method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload/uploadFile3.do">
<label>文件名称:</label>
<input type="text" name="userName3">
<input type="file" name="fileupload3"/>
<input type="submit" value="提交2"/>
</form>
前台采用form表单同步提交方式。
二、在web-info下建立上传文件夹upload
三、后台java
@RequestMapping(value="uploadFile3.do")
public String uploadFile3(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="fileupload3") MultipartFile file, ModelMap map) {
String userName = request.getParameter("userName3");
System.out.println("userName:"+userName);
if(!file.isEmpty()) {
//上传文件路径
String path = request.getSession().getServletContext().getRealPath("/upload/");
//上传文件名
String filename = file.getOriginalFilename();
File filepath = new File(path,filename);
//判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件当中
try {
file.transferTo(new File(path + File.separator + filename));
map.addAttribute("message", "上传成功哈哈");
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
map.addAttribute("message", "上传异常");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
map.addAttribute("message", "上传异常");
}
} else {
map.addAttribute("message", "参数异常");
}
return "message";
}
四、springmvc.xml配置文件加入配置信息
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小上限,单位为字节(10MB) -->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
五、建立message.jsp页面:
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<title>消息提示</title>
</head>
<body>
${message}
</body>
</html>
tomcat下上传实际路径通过打印可知:D:\testPro\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\mySSM2\upload
参考文章:http://www.cnblogs.com/WJ-163/p/6269409.html