Spring boot 업로드 파일명 중복 피하기
2024. 12. 26. 20:52ㆍJava/Spring Boot
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);
}
'Java > Spring Boot' 카테고리의 다른 글
Spring boot java.lang.IllegalStateException: No primary or single unique constructor found for interface javax.servlet.http.HttpServletRequest (1) | 2024.12.28 |
---|---|
Spring boot 외부 디렉토리를 static으로 인식하기 (0) | 2024.12.27 |
Spring boot 파일업로드 OutOfMemoryError 고려사항 (0) | 2024.12.26 |
Spring boot 업로드 디렉토리 설정하기 (0) | 2024.12.26 |
Spring boot Sencha 연동 파일 업로드 구성 (0) | 2024.12.26 |