spring boot 中对修改的头像进行更改,同时删除原来的头像,头像是初始头像不删除,信息保存session,实时更新

 @RequestMapping(value = "/touxiang", method = RequestMethod.POST)
    public String updateversion(MultipartFile img, HttpServletRequest req) {
        String filename = null;
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/img";
        /ssion中拿到userid
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute("userinfo");
        int userid = userInfo.getUid();
        //拿到要删除的图片地址
        String originimgpath = userInfo.getImgpath();
        String delpath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static" + originimgpath;
        if (img != null) {
            //删除头像前先判断是否是默认图片,是的话不删
            if (!originimgpath.equals("/img/firstimg.jpg")) {
                //拿到图片地址,把本地图片删除*/
                File f1 = new File(delpath);
                f1.delete();
            }
            //给图片命名简单随机
            Random random = new Random();
            filename = System.currentTimeMillis() + random.nextInt(100000) * 100 + img.getOriginalFilename();
            System.out.println(filename + "===========================");
            File f = new File(path, filename);
            if (!f.exists()) {
                try {
                    f.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                img.transferTo(f);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //更新数据库的图片字段
        String imgpath = "/img/" + filename;
        sd.updateuserimg(userid, imgpath);
        //更改以后,把最新的userinfo保存到session中
        UserInfo userInfo1 = sd.queryuserinfo(userid);
        session.setAttribute("userinfo", userInfo1);
        return "message/updatemessage";
    }
上一篇:正则表达式


下一篇:Netty 源码深度解析(九) - 编码(上)