因此,当我为用户更新数据时,我遇到了一个错误,即使我已经在数据库中为用户上传了图像,它也想再次上传图像。谁能告诉我如何在不上传图像的情况下保存用户,但上传的图像保留在我的数据库中?
错误是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"; Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您的
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); } }