Web/Spring
[Spring] 파일 업로드/다운로드 (다운로드)
TheCar
2024. 4. 8. 14:48
728x90
반응형
이번엔 다운로드 차례이다.
우선 업로드는 링크로 남겨두자.
https://thecardeveloper.tistory.com/40
[Spring] 파일 업로드/다운로드 (업로드)
오늘은 웹 개발에서 거의 빼놓을 수 없는 파일 업로드/다운로드에 대해서 알아보자. 이 전에 한 번 다룬 적이 있다. 그땐 Servlet을 이용해서 파일 업로드/다운로드를 다뤘다. 하지만 Spring을 이용
thecardeveloper.tistory.com
위 업로드 포스트에서 객체 및 핵심 로직을 구현했기 때문에 다운로드는 컨트롤러만 작성해주면 되겠다.
ItemController.java
1. 업로드한 이미지 파일을 view에서 보기위한 downlaodImage 메서드 생성
2. 업로드한 파일을 내 로컬 PC로 다운로드 하기 위한 downloadAttach 메서드 생성
@ResponseBody
@GetMapping("/images/{filename}")
public Resource downloadImage(@PathVariable String filename) throws MalformedURLException {
//"file:/D:/upload/study/file/asdfkjasldkjflsakdf"
return new UrlResource("file:" + fileStore.getFullPath(filename));
}
@GetMapping("/attach/{itemId}")
public ResponseEntity<Resource> downloadAttach(@PathVariable 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);
}
위 코드에서 보면 downlaodImage는 Resource를 return하고 @ResponseBody 어노테이션을 사용하였는데
downloadAttach처럼 @ResponseBody 어노테이션을 사용하지 않고 ResposenEntity에 Resource를 담아서 return 하는 방식도 가능하다.
item-view.html
<!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>
예시화면
다시 한번 얘기하자면 더욱 깊은 내용은 inflearn 김영한의 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술을 참고하자.
728x90
반응형