springboot文件上传 MultipartFile

用户头像修改

public String updateUser(@RequestParam("avatarUrl") MultipartFile multipartFile, User newUser, HttpServletRequest request) throws IOException {
        User oldUser =(User) request.getSession().getAttribute("user");
        try{
//            获取图片文件名
            String filename = multipartFile.getOriginalFilename();
//            获取项目运行的绝对路径  '/static/img/avatar/'是虚拟的
            String path = request.getSession().getServletContext().getRealPath("/static/img/avatar/");
            System.out.println("path====="+path);
//            创建文件存放的目录
            File pathFile = new File(path);
            if(!pathFile.isDirectory()){
                pathFile.mkdirs();
            }
            File disk = new File(pathFile, filename);
            System.out.println("修改之后得头像路径=="+disk.getPath());
            multipartFile.transferTo(disk);
            String oldName = oldUser.getAvatar().substring(oldUser.getAvatar().lastIndexOf("/"));
            System.out.println("旧名字=="+oldName);
            File oldAvatar = new File( pathFile , oldName);
            System.out.println("修改之前的头像路径=="+ oldAvatar.getPath());
            if(oldAvatar.exists()) {
                boolean delete = oldAvatar.delete();
            }
            oldUser.setAvatar(disk.getPath());
        }catch (Exception e){
            e.printStackTrace();
        }
        userService.updateUser(oldUser,newUser,request);
        return "redirect:/admin/blogs";
    }

你可能感兴趣的:(java,tomcat,spring,intellij-idea)