基于ssm框架的图片上传

预添加

@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";
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值