本人在设置头像上传更新的时候,发现有个更新的BUG,上传好之后也能显示出来,但是这个时候点击更新,没有重新上传图片,就出来了头像丢失的问题。后来发现controller判断头像是否为空出现了问题
原本判断是 if(file!=null),原本是想判断file是否为空就可以知道修改的时候有没有更改头像,如果不为空则证明更改了头像,那么后面就是添加头像的操作了。
然而关键就在这里,其实这个判断有问题,这样判断是没法判断出file到底改变了没有,也就是说即使没有更改头像,它也会认为这个地方不为空。
所以我就更改了这个判断语句,if(!file.isEmpty())同时sql语句也使用了动态sql语句
<update id="update" parameterType="User">
update user set
u_password=#{uPassword},
u_name=#{uName},
u_tel=#{uTel},
u_email=#{uEmail},
<if test="uPhoto!=null">u_photo=#{uPhoto}</if>
where u_id=#{uId}
</update>
附controller修改头像的源码:
@RequestMapping(value="/user/update.action",method={RequestMethod.POST})
public String update(User user,HttpServletRequest request,
@RequestParam("photo") MultipartFile file){
//1.判断上传的头像是否为空
if(!file.isEmpty()){
//头像上传
//2、指定上传目录
String str=request.getServletContext().getRealPath("//upload//user");
System.out.println(str);
//3、如果路径不存在,创建此路径
File path=new File(str);
if(!path.exists()){
path.mkdirs();
}
//4、获取名字
String name=file.getOriginalFilename();
//5、防止名字重复
name=UUID.randomUUID()+name;
//6、拼接路径 路径加名字 文件
File desPath= new File(path, name);
//7、文件上传
try {
//要上传的路径 , 文件-------字节数组
FileUtils.writeByteArrayToFile(desPath, file.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//8、把改路径设置到user里面数据库里D://xxxx//upload//user/xx.jpg
user.setuPhoto("user//"+name);
}
userService.update(user);
//数据在session中,修改之后需要刷新session里面的值
User user1=userService.findUser_Class(user.getuId());
request.getSession().setAttribute("user_class", user1);
return "kstj/kstj";
}