본문 바로가기
개발/Spring

[Spring] 파일 업로드 시 파일명 변경하기

by devhooney 2022. 6. 27.
728x90

파일 업로드 시 파일명 변경이 필요함

- 개발하는데, 파일명을 강제로 바꿔줘야 하는 일이 발생했다.

- Javascript의 input:file에서는 변경이 불가능하다.

- Java에서 파일을 받아 파일명을 변경했다.

@PostMapping("/save")
@ResponseBody
public long save(@RequestParam("imgCoverFile") MultipartFile file) {
	File targetFile = new File("/path/path2/" + newFileName);
  	InputStream fileStream = file.getInputStream();
    FileUtils.copyInputStreamToFile(fileStream, targetFile); 
}

 

- Apache Commons IO의 FileUtils를 통해 쉽게 구현.

- new File에는 저장하고 싶은 경로와 파일명을 넣으면 원하는 경로에 원하는 이름으로 저장된다.

- Apache Commons IO을 사용하고 싶으면 https://mvnrepository.com/artifact/commons-io/commons-io 에서 원하는 버전으로 gradle/maven 골라서 셋팅해주면 된다.

 

728x90