search

Home  >  Q&A  >  body text

Avoid errors when editing data without uploading user images

So when I was updating the data for the user, I ran into an error where it wanted to upload the image again even though I had already uploaded the image for the user in the database. Can anyone tell me how to save the user without uploading the image, but keep the uploaded image in my database?

The error is java.IOException: Unable to save image file:

Caused by: java.nio.file.DirectoryNotEmptyException: profile-image/4

This is my controller

@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粉707235568234 days ago354

reply all(1)I'll reply

  • P粉156532706

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

    There is a bug in your FileUploadUtil class. This directory should be created only if the directory does not exist exists:

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

    reply
    0
  • Cancelreply