Avoid errors when editing data without uploading user images
P粉707235568
P粉707235568 2024-03-31 12:44:01
0
1
320

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粉707235568
P粉707235568

reply all(1)
P粉156532706

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);
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!