파일 업로드/다운로드
업로드
클라이언트에서 서버로 파일을 전송할 때는 form 태그의 enctype 속성을 multipart/form-data 로 설정해줘야 한다.
1
2
3
4
5
6
7
<form th:action="/upload/new" 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>
위 상태에서 submit 하면 text 타입의 input 값과 첨부한 파일이 서버로 전송된다.
전송할 때 HTTP 메시지는 다음과 같은 형태를 지닌다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
POST /upload/new HTTP/1.1
Host: localhost:8080
Content-Type: multipart/form-date; boundary=----WebKitFormBoundaryyaXcMeMH4g0cFgKF
----WebKitFormBoundaryyaXcMeMH4g0cFgKF
Content-Disposition: form-data; name="name"
spring
----WebKitFormBoundaryyaXcMeMH4g0cFgKF
Content-Disposition: form-data; name="file"; filename="image.png"
Content-Type: image/png
3l2i3jl3ijflaj39fj9392laiwielfieflawiejfiejlaijw...
----WebKitFormBoundaryyaXcMeMH4g0cFgKF--
업로드한 파일을 컨트롤러에서 받을 때는 MultipartFile
인터페이스를 사용한다.
1
2
3
4
@PostMapping("/upload/new")
public String fileUpload(@RequestParam String name, @RequestParam MultipartFile file) {
...
}
이 때 MultipartFile 변수명과 input 태그의 name 을 맞춰줘야 한다. 그리고 @RequestParam 뿐만 아니라 MultipartFile 필드가 정의된 클래스를 만들고 @ModelAttribute 를 사용하는 것도 가능하다.
파일 저장
MultipartFile 객체의 transferTo()
메서드를 사용하면 파일을 실제 디스크에 저장할 수 있다.
1
2
3
4
5
6
7
@PostMapping("/upload/new")
public String fileUpload(@RequestParam String name, @RequestParam MultipartFile file) {
...
String fileDir = "/Users/user/upload/" + file.getOriginalFilename();
file.transferTo(new File(fileDir)); // 디렉터리가 없으면 오류가 발생한다.
...
}
다운로드
서버에 업로드한 파일을 다운로드할 때는 UrlResource
클래스를 사용한다.
1
2
3
4
5
6
7
8
9
10
@GetMapping("/download/{filename}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
...
UrlResource resource = new UrlResource("file:/Users/user/upload/" + filename);
String encodedFilename = UriUtils.encode(filename, StandardCharsets.UTF_8); // 다운받는 파일 이름이 한글일 때 깨지지 않도록 하기 위함
String contentDisposition = "attachment; filename=\"" + encodedFilename + "\""; // 클라이언트에게 이 응답은 파일다운로드 라고 알려주기 위함
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.body(resource);
}
관련 옵션
- spring.servlet.multipart.max-file-size
- 파일 하나의 최대 사이즈를 설정할 수 있다. 기본은 1MB
- spring.servlet.multipart.max-request-size
- 하나의 요청에 최대 사이즈를 설정할 수 있다. 기본은 10MB
- spring.servlet.multipart.enabled
- multipart 요청 사용 유무를 설정할 수 있다. 기본은 true
This post is licensed under CC BY 4.0 by the author.