标签:
1.导包
com.springsource.org.apache.commons.fileupload-1.2.0.jar com.springsource.org.apache.commons.io-1.4.0.jar
2.spring配置文件增加上传的bean
<!--文件上传-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>头像上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/upload.action" method="POST" enctype="multipart/form-data">
<input type="file" name="headImage"/><br/>
<input type="submit" value="上传">
</form>
</body>
</html>
4.处理头像方法
@RequestMapping(value = "upload")
public String upload(Model model, MultipartFile headImage, HttpServletRequest request)
throws IOException {
//设置保存目录
String dirs = "upload";
if (headImage != null){
//调用图片处理方法(在另一博文中)
String fileName = Upload.UploadImg(headImage, request, dirs);
//回显头像
model.addAttribute("myImage", request.getContextPath()+"/"+dirs+"/"+fileName);
//回显消息
model.addAttribute("message", "上传成功");
} else {
model.addAttribute("message", "上传失败");
}
return "success";
}
5.回显页面
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>结果</title>
</head>
<body>
${message}
<br/>
<img src="${myImage }" />
</body>
</html>
标签:
原文地址:http://www.cnblogs.com/zenzzat/p/5545555.html