스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 - (58) 스프링 부트 - 파일 업로드 - 업로드, 다운로드 예제
인프런 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술편을 학습하고 정리한 내용 입니다.
예제로 구현하는 파일 업로드, 다운로드
실제 파일이나 이미지를 업로드, 다운로드할 때는 몇 가지 고려할 점이 있는데, 구체적인 예제로 알아보자.
요구 사항
- 상품을 관리
- 상품 이름
- 첨부 파일 하나
- 이미지 파일 여러 개
- 첨부 파일을 업로드 다운로드 할 수 있다.
- 업로드한 이미지를 웹 브라우저에서 확인할 수 있다.
코드 구현
Item - 상품 도메인
hello.upload.domain.Item
1
2
3
4
5
6
7
@Data
public class Item {
private Long id;
private String itemName;
private UploadFile attachFile;
private List<UploadFile> imageFiles;
}
UploadFIle - 업로드 파일 정보 보관
hello.upload.domain.UploadFile
1
2
3
4
5
6
7
8
9
10
11
@Data
public class UploadFile {
private String uploadFileName;
private String storeFileName;
public UploadFile(String uploadFileName, String storeFileName) {
this.uploadFileName = uploadFileName;
this.storeFileName = storeFileName;
}
}
- uploadFileName : 실제 원본 파일 이름
- storeFileName : uuid로 변경된 서버 파일 이름
고객이 업로드한 파일을 그대로 저장하면 안됨. 파일 명 중복되지 않도록 uuid 사용
ItemRepository - 상품 리포지토리
hello.upload.domain.ItemRepository
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Repository
public class ItemRepository {
private final Map<Long, Item> store = new HashMap<>();
private long sequence = 0L;
public Item save(Item item) {
item.setId(++sequence);
store.put(item.getId(), item);
return item;
}
public Item findById(long id) {
return store.get(id);
}
}
DB 따로 연동은 안하고 메모리에서만 동작하도록 제작.
FileStore - 파일 저장과 관련된 업무 처리
hello.upload.file.FileStore
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@Component
public class FileStore {
@Value("${file.dir}")
private String fileDir;
public String getFullPath(String fileName) {
return fileDir + fileName;
}
public List<UploadFile> storeFiles(List<MultipartFile> multipartFiles) throws IOException {
List<UploadFile> storeFileResult = new ArrayList<>();
for (MultipartFile multipartFile : multipartFiles) {
if (!multipartFile.isEmpty()) {
storeFileResult.add(storeFile(multipartFile));
}
}
return storeFileResult;
}
public UploadFile storeFile(MultipartFile multipartFile) throws IOException {
if (multipartFile.isEmpty()) {
return null;
}
String originalFilename = multipartFile.getOriginalFilename();
String storeFileName = createStoreFileName(originalFilename);
multipartFile.transferTo(new File(getFullPath(storeFileName)));
return new UploadFile(originalFilename, storeFileName);
}
private String createStoreFileName(String originalFilename) {
String ext = extractExt(originalFilename);
//서버에 저장할 파일명
String uuid = UUID.randomUUID().toString();
return uuid + "." + ext;
}
private String extractExt(String originalFilename) {
int pos = originalFilename.lastIndexOf(".");
return originalFilename.substring(pos + 1);
}
}
멀티파트 파일을 서버에 저장하는 역할을 담당.
createStoreFileName: 파일 이름을UUID로 새로 생성해서 바꿔주는 메서드extractExt: 원본 파일의 확장자를 추출하는 메서드storeFile: 파일을 실제 서버에 업로드 하는 메서드storeFiles: 이미지는 여러 장을 올리기 때문에 for문으로storeFile을 호출하기 위한 메서드MultipartFile→UploadFile이 작업도 같이 들어가 있다.
이제 핵심적인 기능 구현은 끝났다. 컨트롤러와 뷰 템플릿을 만들자.
ItemForm
hello.upload.controller.ItemForm
1
2
3
4
5
6
7
8
@Data
public class ItemForm {
private Long id;
private String itemName;
private MultipartFile attachFile;
private List<MultipartFile> imageFiles;
}
상품 저장용 폼.
List<MultipartFile> imageFiles: 이미지를 다중 업로드 하기 위해MultipartFile를 사용했다.MultipartFile attachFile: 멀티파트는@ModelAttribute에서 사용할 수 있다.
ItemController
hello.upload.controller.ItemController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
@Slf4j
@RequiredArgsConstructor
@Controller
public class ItemController {
private final ItemRepository itemRepository;
private final FileStore fileStore;
@GetMapping("/items/new")
private String newItem() {
return "item-form";
}
@PostMapping("/items/new")
private String saveItem(@ModelAttribute ItemForm form, RedirectAttributes redirectAttributes) throws IOException {
UploadFile attachFile = fileStore.storeFile(form.getAttachFile());
List<UploadFile> storeImageFiles = fileStore.storeFiles(form.getImageFiles());
// 데이터베이스에 저장
Item item = new Item();
item.setItemName(form.getItemName());
item.setAttachFile(attachFile);
item.setImageFiles(storeImageFiles);
itemRepository.save(item);
redirectAttributes.addAttribute("itemId", item.getId());
return "redirect:/items/{itemId}";
}
@GetMapping("/items/{id}")
public String items(@PathVariable("id") Long id, Model model) {
Item item = itemRepository.findById(id);
model.addAttribute("item", item);
return "item-view";
}
@ResponseBody
@GetMapping("/images/{filename}")
public Resource downloadImage(@PathVariable("filename") String filename) throws MalformedURLException {
return new UrlResource("file:" + fileStore.getFullPath(filename));
}
@GetMapping("/attach/{itemId}")
public ResponseEntity<Resource> downloadAttach(@PathVariable("itemId") Long itemId) throws MalformedURLException {
Item item = itemRepository.findById(itemId);
String storeFileName = item.getAttachFile().getStoreFileName();
String uploadFileName = item.getAttachFile().getUploadFileName();
UrlResource resource = new UrlResource("file:" + fileStore.getFullPath(storeFileName));
log.info("uploadFileName={}", uploadFileName);
String encodedUploadFileName = UriUtils.encode(uploadFileName, StandardCharsets.UTF_8);
String contentDisposition = "attachment; filename=\"" + encodedUploadFileName + "\"";
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.body(resource);
}
}
@GetMapping("/items/new"): 등록 폼을 보여준다.@PostMapping("/items/new"): 폼의 데이터를 저장하고 보여주는 화면으로 리다이렉트 한다.@GetMapping("/items/{id}"): 상품을 보여준다.@GetMapping("/images/{filename}"):<img>태그로 이미지를 조회할 때 사용한다.
UrlResource로 이미지 파일을 읽어서@ResponseBody로 이미지 바이너리를 반환한다.@GetMapping("/attach/{itemId}"): 파일을 다운로드 할 때 실행한다. 굳이 id를 받을 필요는 없지만, 파일 다운로드 시 권한을 체크하는 등 복잡한 상황까지 가정한다 생각하고 id를 요청하도록 했다. 파일 다운로드 시에는 고객이 업로드한 파일 이름으로 다운로드 하는게 좋다.
이 때는Content-Disposition헤더에attachment; filename="업로드 파일명"값을 주면 된다.
등록 폼 뷰
templates/item-form.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<div class="py-5 text-center">
<h2>상품 등록</h2>
</div>
<form th:action method="post" enctype="multipart/form-data">
<ul>
<li>상품명 <input type="text" name="itemName"></li>
<li>첨부파일<input type="file" name="attachFile" ></li>
<li>이미지 파일들<input type="file" multiple="multiple" name="imageFiles" ></li>
</ul>
<input type="submit"/>
</form>
</div> <!-- /container -->
</body>
</html>
다중 파일을 업로드 하려면 multiple="multiple" 옵션을 넣어 주면 된다.
ItemForm의 다음 코드에서 여러 이미지 파일을 받을 수 있다.
private List<MultipartFile> imageFiles;
조회 뷰
templates/item-view.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<div class="py-5 text-center">
<h2>상품 조회</h2>
</div>
상품명: <span th:text="${item.itemName}">상품명</span><br/>
첨부파일: <a th:if="${item.attachFile}" th:href="|/attach/${item.id}|" th:text="${item.getAttachFile().getUploadFileName()}" /><br/>
<img th:each="imageFile : ${item.imageFiles}" th:src="|/images/${imageFile.getStoreFileName()}|" width="300" height="300"/>
</div> <!-- /container -->
</body>
</html>
첨부 파일은 링크로 걸어두고, 이미지는 <img> 태그를 반복해서 출력한다.
th:src="|/images/${imageFile.getStoreFileName()}|"로 이미지 뷰 컨트롤러를 호출
결과

다음과 같이 첨부 파일은 1개 이미지 파일은 여러 개를 등록할 수 있다.


제출 하면 다음과 같이 uuid로 파일이 저장되고, 뷰에선 잘 보여준다.

다운로드 하면 원본 파일 이름으로 잘 다운로드 된다.
댓글남기기