预添加
@RequestMapping("/updatePic")
public String UpdatePic(Model model,HttpSession session) {
User user=(User) session.getAttribute("user");
User u=personalCenterService.selectUser(user.getUser_id());
model.addAttribute("m",u);
return "picUpdate";
}
此为jsp页面
<div class="right">
<img src="${pageContext.request.contextPath}/picUpLoad/${m.user_picname}">
</div>
<h5 align="center">${picerror}</h5>
<h5 align="center">${ms}</h5>
<form action="${pageContext.request.contextPath}/picUpLoad.do" method="post" enctype="multipart/form-data">
<p style="text-align: center;">请选择新头像:<input type="file" name="pic" required="required"></p>
<input type="hidden" name="sid" value="${sessionScope.user.user_id}">
<p style="text-align: center;"><button type="submit">立即修改</button></p>
<p style="text-align: center;"><button
onclick="window.location.href='${pageContext.request.contextPath}/emp_view/returns.do'">返回</button></p>
</form>
后台代码存图片的代码
@RequestMapping("/picUpLoad")
public String picUpLoad(MultipartFile pic,HttpSession session, String sid, Model model, HttpServletRequest req) {
String name = pic.getOriginalFilename();
String postfix = name.substring(name.lastIndexOf("."));
if (".jpg".equals(postfix) || ".png".equals(postfix) || ".bmp".equals(postfix) || ".psd".equals(postfix)
|| ".gif".equals(postfix) || ".pdf".equals(postfix) || ".svg".equals(postfix)) {
String picPath=req.getServletContext().getRealPath("/picUpLoad");
Date date=new Date();
SimpleDateFormat si = new SimpleDateFormat("YYYY-MM-dd-hh-mm-ss");
String picdate = si.format(date);
int x=(int) (Math.random()*100);
String picName=picdate+x+name;
File f=new File(picPath,picName);
try {
pic.transferTo(f);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
model.addAttribute("picerror","图片上传失败");
return "picUpdate";
}
int id=Integer.parseInt(sid);
int y =personalCenterService.picUpdate(picName,id);
if (y>0) {
model.addAttribute("ms","头像更换成功");
User us=(User) session.getAttribute("user");
us.setUser_picname(picName);
session.setAttribute("user", us);
User u=personalCenterService.selectUser(us.getUser_id());
model.addAttribute("m",u);
return "picUpdate";
}else {
model.addAttribute("ms","头像更换失败");
return "picUpdate";
}
} else {
model.addAttribute("picerror", "图片格式错误!");
return "picUpdate";
}
}