2. 파일 업로드 (Spring)
1. Multipart란
일단 Multipart란 클라이언트가 요청을 보낼 때, http 프로토콜의 바디 부분에 데이터를 여러 부분으로 나눠서 보내는 것을 말한다. 웹 클라이언트가 서버에게 파일을 업로드할 경우, 저번 Servlet 파일 업로드 편에서 알 수 있듯이 파일을 한 번에 여러 개 전송을 하면 body 부분도 파일이 여러 부분으로 연결되어 전송이 된다.
2. MultipartResolver란
Multipart 지원 기능을 이용하려면 먼저 MultipartResolver를 스프링 설정 파일에 등록해 주어야 하는데 스프링 부트는 해당 부분을 자동으로 등록해주니 따로 설정할 필요가 없다.
MultipartResolver는 Multipart 형식으로 데이터가 전송된 경우, 해당 데이터를 스프링 MVC에서 사용할 수 있도록 변환해주기 때문에 Muiltpart 객체를 컨트롤러에 전달하는 역할을 한다고 볼 수 있다.
2. MultipartFile란
스프링은 MultipartFile 이라는 인터페이스로 파일 업로드를 매우 편리하게 지원한다.
업로드한 파일 및 데이터를 구하는 용도로 사용이 된다.
3. MultipartFile 예제
< application.properties >
//파일 업로드 경로 추가
file.dir=C:/Users/GON/file/
원하는 경로에 폴더를 미리 만들고 진행한다.
< uploadForm >
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<h4 class="mb-3">스프링 업로드</h4>
<form th:action method="post" enctype="multipart/form-data">
<ul>
<li>이름<input type="text" name="name"></li>
<li>파일<input type="file" name="file"></li>
</ul>
<input type="submit"/>
</form>
</div> <!-- /container -->
</body>
</html>
파일 업로드를 할 때는 form의 enctype = multipart/form-data로 작성해야하고, method = post여야 합니다.
그래야 MultipartResolver가 multipartFile객체를 컨트롤러에 전달할 수 있다.
< UploadController >
@Value("C:/Users/GON/file/")
private String fileDir;
@GetMapping("/upload")
public String uploadGet(){
return "uploadForm";
}
@PostMapping("/upload")
public String uploadPost(@RequestParam String name,
@RequestParam MultipartFile file) throws IOException {
if(!file.isEmpty()){
String fullPath = fileDir + file.getOriginalFilename();//업로드한 파일명
//파일저장
file.transferTo(new File(fullPath));
}
return "uploadForm";
}
업로드한 파일을 전달받는 방법은 @RequestParam 어노테이션이 적용된 MultipartFile 타입의 파라미터를 사용하는 것이다. 이 경우 다음 코드와 같이 @RequestParam 어노테이션과 MultipartFile 타입의 파라미터를 이용해서 업로드 파일 데이터를 전달받을 수 있다.
file.getOriginalFilename()을 사용해 업로드한 파일명을 가져와서 파일을 저장할 경로에 붙여주고 file.transferTo()를 통해 파일을 지정한 해당 폴더에 저장해 준다.
실행해 보면 해당 경로에 파일이 잘 저장되어있는 것을 알 수 있다.
전편에 서블릿이 제공하는 Part를 이용한 방식보다 보다 편리하게 업로드를 구현할 수 있다는 것을 알 수 있다.