Java/Spring Boot
Spring boot 업로드 파일명 중복 피하기
바리새인
2024. 12. 26. 20:52
filePath 정보를 계속 변경해서 while문으로 존재여부를 확인하는게 중요
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
// Define the directory where files will be saved
String uploadDir = "uploads/";
// Ensure the directory exists
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
// Get the original filename and extension
String originalFilename = file.getOriginalFilename();
String name = originalFilename.contains(".")
? originalFilename.substring(0, originalFilename.lastIndexOf('.'))
: originalFilename;
String extension = originalFilename.contains(".")
? originalFilename.substring(originalFilename.lastIndexOf('.'))
: "";
// Initialize counter by finding existing files with matching patterns
int counter = 0;
String newFilename = originalFilename;
Path filePath = uploadPath.resolve(newFilename);
// Increment counter until no duplicate is found
while (Files.exists(filePath)) {
counter++;
newFilename = name + "(" + counter + ")" + extension;
filePath = uploadPath.resolve(newFilename);
}
// Save the uploaded file with a unique name
Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
return ResponseEntity.ok("File uploaded successfully as " + newFilename);
}