首页  >  问答  >  正文

在不上传用户图像的情况下编辑数据时避免错误

因此,当我为用户更新数据时,我遇到了一个错误,即使我已经在数据库中为用户上传了图像,它也想再次上传图像。谁能告诉我如何在不上传图像的情况下保存用户,但上传的图像保留在我的数据库中?

错误是java.IOException:无法保存图像文件:

由以下原因引起:java.nio.file.DirectoryNotEmptyException:profile-image/4

这是我的控制器

@PostMapping("/profile/save")
public String saveProfile(Profile profile, Model model, @RequestParam("image") MultipartFile multipartFile,@RequestParam(value="userId", required=false) Long userId) throws IOException {
profile.setUser(userRepo.findById(userId).get());
String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename()) ;
String uploadDir - "profile-image/"+ profile.getId();
FileUploadUtil.saveFile(uploadDir, fileName, multipartFile);
profile.setProfileImg(fileName);
profileService.saveProfile(profile);
return "redirect:/user/profile";

P粉707235568P粉707235568185 天前286

全部回复(1)我来回复

  • P粉156532706

    P粉1565327062024-04-01 09:38:55

    您的 FileUploadUtil 类中存在错误。仅当该目录不存在存在时才应创建该目录:

    public static void saveFile(String uploadir, String fileName, MultipartFile multipartFile) throws IOException {
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        try (InputStream inputStream = multipartFile.getInputStream()) {
            Path filePath = uploadPath. resolve(fileName);
            System.out.printIn(filePath.toFile()-getAbsolutePath()+"File Path*******");
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException ioe) {
            throw new IOException("Could not save image file: " + fileName, ioe);
        }
    }

    回复
    0
  • 取消回复