파일업로드, 파일명 중복제거

 

Summry

본 문서에서는 새로운 파일을 업로드할때 업로드된 파일명과 중복되면 그대로 덮어 쓰게 된다는점을 해결하기 위해 UUID를 이용한 파일명 중복제거 방법을 정리한다.

send me email if you have any questions.


방법

  1. 저장 디렉토리에 중복되는 파일이 존재하면 파일명에 뒤에 숫자를 붙이는 방법.
    • 파일명에 업로드시간 즉 timestamp 를 붙여주는 방법.
  2. 랜덤한 문자열을 생성해 파일명에 붙여주는 방법.
    • UUID를 생성해서 파일명을 랜덤하게 생성시켜주는 방법.

UUID example code

@PostMapping("/postImage") 
public int uploadPostImage(@RequestPart List<MultipartFile> files, HttpServletResponse res)
    throws Exception {
String originName = "";
String saveName = "";
long size;
int post_index = communityService.checkPostIndex();
String path = "path";
UUID uuid = UUID.randomUUID();

path += post_index;

for (MultipartFile file : files) {
    originName = file.getOriginalFilename();
    size = file.getSize();
    
    // DB에 저장할 경로(static resource 조회를 위함)
    path = "/static/images/post/" + post_index;

    // filename의 중복을 제거하기 위해 UUID 사용
    // 무작위 넘버 뒤에 본래의 파일 이름 붙임
    saveName = uuid.toString() + "_" + originName;

    int result = communityService.uploadPostImage(null, post_index, originName, size, path);
    if (result > 0) {

    file.transferTo(new File(path));
    } else {
    res.setStatus(StatusCode.serverErr);
    return StatusCode.serverErr;
    }
}

res.setStatus(StatusCode.Created);
return StatusCode.Created;
}

업로드 결과 아래처럼 저장된다.
246b3197-00c8-4d15-a973-1b40c3bc9963_lena.jpg

Reference

스프링 - 파일업로드 연습2(파일명 중복제거) - 포포의 개발공부방