업로드한 파일을 컨트롤러에서 처리하고자 할 때에는 MultipartFile을 이용합니다. 파일이 하나인 경우는 MultipartFile을 변수 타입으로 하고 여러 개인 경우 List<MultipartFile>을 변수 타입으로 합니다.
HTML
<form method="post" action="/[업로드할_컨트롤러_주소]" enctype="multipart/form-data">
<input multiple type="file" name="files">
<button>submit</button>
</form>
<form> 태그에 enctype="multipart/form-data"를 추가합니다. <input>에서 multiple이 있으면 여러 파일 업로드 허용, 없으면 하나의 파일만 허용합니다.
단일 파일 업로드
import org.springframework.web.multipart.MultipartFile;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
// .......
// 컨트롤러 내부에 위치
@PostMapping(DEFAULT_URI + "/single")
public String uploadSingle(@RequestParam("files") MultipartFile file) throws Exception {
String rootPath = FileSystemView.getFileSystemView().getHomeDirectory().toString();
String basePath = rootPath + "/" + "single";
String filePath = basePath + "/" + file.getOriginalFilename();
File dest = new File(filePath);
files.transferTo(dest); // 파일 업로드 작업 수행
return "uploaded";
}
여러 파일 업로드
import org.springframework.web.multipart.MultipartFile;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.util.List;
// .......
// 컨트롤러 내부에 위치
@PostMapping(DEFAULT_URI + "/multi")
public String uploadMulti(@RequestParam("files") List<MultipartFile> files) throws Exception {
String rootPath = FileSystemView.getFileSystemView().getHomeDirectory().toString();
String basePath = rootPath + "/" + "multi";
// 파일 업로드(여러개) 처리 부분
for(MultipartFile file : files) {
String originalName = file.getOriginalFilename();
String filePath = basePath + "/" + originalName;
File dest = new File(filePath);
file.transferTo(dest);
}
return "uploaded";
}





6개의 댓글
df · 2021년 2월 21일 10:55 오후
파일이름 중복은 어떻게 처리해야되나요?
yoonbumtae (BGSMM) · 2021년 2월 22일 1:59 오후
안녕하세요.
File 클래스를 이용해 이미 중복된 파일이 있다면 새로운 파일 이름을 부여하는 방법을 사용합니다.
이 글의 예제는 너무 단순화되어 있습니다. 파일명을 원본 파일명으로 그대로 저장하면 안되고, UUID와 데이터베이스를 이용해서 원본 파일명과 저장 파일명을 별도로 구분해서 지정해야 합니다.
감사합니다.
df · 2021년 2월 22일 8:55 오후
답변감사해요. 다행히 업로드 성공도 하고 uuid 머시기 통해서 중목 이름도 처리했습니다. 그런데 맥+vscode 사용중인데 게시판에서 업로드한 사진이 떠야되는데 엑박이네요…이상해서 사진이 있는 폴더에 따로 html문서를 만들어 img src=”” 로 불러봐도 그 폴더에 있는 사진은 죽어라 안뜨는데 맥에 다른 설정이 들어가있는걸까요…
yoonbumtae (BGSMM) · 2021년 2월 22일 11:03 오후
안녕하세요.
저는 이클립스나 인텔리제이를 쓰기 때문에 해당 문제는 잘 모릅니다만..
프로젝트 내부 폴더에 파일을 저장하고 불러오려고 하면 처리가 복잡해서 외부 폴더를 만들고 (예: Users/xxx/app/resources/) 거기에 저장 및 불러오기 하면 오류가 안났던 걸로 기억하고 있습니다.
그리고 img src의 경로를 스태틱 경로 그대로 지정하면 안되고 컨트롤러를 하나 만들어서 간접적으로 이미지 파일을 가져오는 방식을 사용해야 될 것 같습니다.
감사합니다.
ㅁㄴㅇㄹ · 2021년 4월 30일 7:05 오후
감사합니다 이거 보고 오랫동안 궁금했던 사용자 바탕화면 주소로 가는 방법 알게 되었습니다
스프링 부트(Spring Boot) 미디 플레이어 만들기 (2): 업로드 페이지, 임시 재생 플레이어 만들기 - BGSMM · 2020년 8월 15일 5:38 오후
[…] 스프링 부트(Spring Boot): 파일 업로드 처리하기 (한 개, 여러 개) […]