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";
    }

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卧龙不言

欢迎关注java基础笔记公众号

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值