因此,當我為用戶更新資料時,我遇到了一個錯誤,即使我已經在資料庫中為用戶上傳了圖像,它也想再次上傳圖像。誰能告訴我如何在不上傳圖像的情況下保存用戶,但上傳的圖像保留在我的資料庫中?
錯誤是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粉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); } }