서블릿과 파일 업로드2
파일 저장 경로
--application.properties
file.dir=파일 업로드 경로 설정 (예): /Users/kimyounghan/study/file/
주의
1. 꼭 해당 경로에 실제 폴더를 미리 만들어두자.
2. application.properties 에서 설정할 때 마지막에 / (슬래시)가 포함된 것에 주의하자.
@Value("${file.dir}")
private String fileDir;
org.springframework.beans.factory.annotation.Value
application.properties 에서 설정한 file.dir 의 값을 주입받음
@PostMapping("/upload")
public String saveFileV2(HttpServletRequest request) throws ServletException, IOException {
Collection<Part> parts = request.getParts();
for (Part part : parts) {
log.info("==== PART ====");
log.info("name={}", part.getName());
Collection<String> headerNames = part.getHeaderNames();
for (String headerName : headerNames) {
log.info("header {}: {}", headerName, part.getHeader(headerName));
}
//편의 메서드
//content-disposition; filename
log.info("submittedFilename={}", part.getSubmittedFileName());
log.info("size={}", part.getSize());
//데이터 읽기
InputStream inputStream = part.getInputStream();
String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
log.info("body={}", body);
//파일에 저장하기
if(StringUtils.hasText(part.getSubmittedFileName())){
String fullPath = fileDir + part.getSubmittedFileName();
log.info("파일 저장 fullPath={}", fullPath);
part.write(fullPath);
}
}
return "upload-form";
}
멀티파트 형식은 전송 데이터를 하나하나 각각 부분( Part )으로 나누어 전송한다. parts 에는 이렇게 나누어진 데이터가 각각 담긴다. 서블릿이 제공하는 Part 는 멀티파트 형식을 편리하게 읽을 수 있는 다양한 메서드를 제공한다.
Part 주요 메서드
part.getSubmittedFileName() : 클라이언트가 전달한 파일명
part.getInputStream(): Part의 전송 데이터를 읽을 수 있다.
part.write(...): Part를 통해 전송된 데이터를 저장할 수 있다.
참고: 큰 용량의 파일을 업로드를 테스트 할 때는 로그가 너무 많이 남아서 다음 옵션을 끄는 것이 좋다. logging.level.org.apache.coyote.http11=debug
다음 부분도 파일의 바이너리 데이터를 모두 출력하므로 끄는 것이 좋다.
log.info("body={}", body);
서블릿이 제공하는 Part 는 편하기는 하지만, HttpServletRequest 를 사용해야 하고, 추가로 파일 부분만 구분하려면 여러가지 코드를 넣어야 한다.
스프링과 파일 업로드
스프링은 MultipartFile 이라는 인터페이스로 멀티파트 파일을 매우 편리하게 지원한다.
@PostMapping("/upload")
public String saveFile(@RequestParam String itemName,
@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
log.info("request={}", request);
log.info("itemName={}", itemName);
log.info("multipartFile={}", file);
if(!file.isEmpty()){
String fullPath = fileDir + file.getOriginalFilename();
log.info("파일 저장 fullPath={}", fullPath);
file.transferTo(new File(fullPath));
}
return "upload-form";
}
== 실행 로그 ==
request=org.springframework.web.multipart.support.StandardMultipartHttpServletRequest@928f0f6
itemName=spring
multipartFile=org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@fa2a0c8
파일 저장 fullPath=C:/Users/HYUNA/study/spring-mvc2/upload/file/image.jpg
업로드하는 HTML Form의 name에 맞추어 @RequestParam 을 적용하면 된다. 추가로 @ModelAttribute 에서도 MultipartFile 을 동일하게 사용할 수 있다.
내부적으로는 서블릿의 기능을 사용하여 동작한다.
MultipartFile 주요 메서드
file.getOriginalFilename() : 업로드 파일 명
file.transferTo(...) : 파일 저장
예제로 구현하는 파일 업로드, 다운로드
실제 파일이나 이미지를 업로드, 다운로드 할 때는 몇가지 고려할 점이 있는데, 구체적인 예제로 알아보자.
요구사항
상품 관리
-상품 이름
-첨부파일 하나
-이미지 파일 여러개
첨부파일을 업로드 다운로드 할 수 있다.
업로드한 이미지를 웹 브라우저에서 확인할 수 있다.
UploadFile - 파일 도메인
@Data
public class UploadFile {
private String uploadFileName;
private String storeFileName;
public UploadFile(String uploadFileName, String storeFileName) {
this.uploadFileName = uploadFileName;
this.storeFileName = storeFileName;
}
}
uploadFileName : 고객이 업로드한 파일명
storeFileName : 서버 내부에서 관리하는 파일명
고객이 업로드한 파일명으로 서버 내부에 파일을 저장하면 안된다. 왜냐하면 서로 다른 고객이 같은 파일이름을 업로드 하는 경우 기존 파일 이름과 충돌이 날 수 있다. 서버에서는 저장할 파일명이 겹치지 않도록 내부에서 관리하는 별도의 파일명이 필요하다.
FileStore - 파일 저장과 관련된 업무 처리
@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()) {
UploadFile uploadFile = storeFile(multipartFile);
storeFileResult.add(uploadFile);
}
}
return storeFileResult;
}
public UploadFile storeFile(MultipartFile multipartFile) throws IOException {
if (multipartFile.isEmpty()) {
return null;
}
String originalFilename = multipartFile.getOriginalFilename();
String storeFileName = createStoreFileName(originalFilename);
//실제 서버에 저장되는 파일명: storeFileName
multipartFile.transferTo(new File(getFullPath(storeFileName)));
return new UploadFile(originalFilename, storeFileName);
}
private String createStoreFileName(String originalFilename) {
String ext = extracted(originalFilename);
String uuid = UUID.randomUUID().toString();
return uuid + ext;
}
private String extracted(String originalFilename) {
int pos = originalFilename.lastIndexOf(".");
return originalFilename.substring(pos);
}
}
멀티파트 파일을 서버에 저장하는 역할
createStoreFileName() : 서버 내부에서 관리하는 파일명은 유일한 이름을 생성하는 UUID 를 사용해서 충돌하지 않도록 한다.
extractExt() : 확장자를 별도로 추출해서 서버 내부에서 관리하는 파일명에도 붙여준다. (for 운영의 편리성)
예를 들어서 고객이 a.png 라는 이름으로 업로드 하면 51041c62-86e4-4274-801d-614a7d994edb.png 와 같이 저장
ItemForm - 상품 저장용 폼
@Data
public class ItemForm {
private Long itemId;
private String itemName;
private MultipartFile attachFile;
private List<MultipartFile> imageFiles;
}
List<MultipartFile> imageFiles : 이미지를 다중 업로드 하기 위해 MultipartFile 리스트를 사용했다.
MultipartFile attachFile : 멀티파트는 @ModelAttribute 에서 사용할 수 있다.
등록 폼 뷰 ( item-form )
<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>
imageFiles: 다중 파일 업로드를 위해 multiple="multiple".
컨트롤러에서 스프링에 의해 다중 파일도 리스트로 받아진다. ItemForm의 private List<MultipartFile> imageFiles;
ItemController
@Slf4j
@Controller
@RequiredArgsConstructor
public class ItemController {
private final ItemRepository itemRepository;
private final FileStore fileStore;
@GetMapping("/items/new")
public String newItem(@ModelAttribute ItemForm itemForm) {
return "item-form";
}
@PostMapping("/items/new")
public String saveItem(@ModelAttribute ItemForm form, RedirectAttributes redirectAttributes) throws IOException {
//업로드 파일 스토리지에 저장
MultipartFile multipartFile = form.getAttachFile();
UploadFile attachFile = fileStore.storeFile(multipartFile);
log.info("text file={}", multipartFile.getOriginalFilename());
List<MultipartFile> multipartFiles = form.getImageFiles();
List<UploadFile> storeImageFiles = fileStore.storeFiles(multipartFiles);
//데이터베이스에 저장 (파일의 스토리지 경로)
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/{itemId}")
public String items(@PathVariable("itemId") Long id, Model model){
Item item = itemRepository.findById(id);
model.addAttribute("item", item);
return "item-view";
}
@ResponseBody
@GetMapping("/images/{filename}")
public Resource downloadImage(@PathVariable String filename) throws MalformedURLException {
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);
}
}
- @GetMapping("/items/new") : 등록 폼을 보여준다.
- @PostMapping("/items/new") : 폼의 데이터를 저장하고 보여주는 화면으로 리다이렉트 한다.
- @GetMapping("/items/{itemId}") : 상품을 보여준다.
- @GetMapping("/images/{filename}") : <img> 태그로 이미지를 조회할 때 사용한다. UrlResource 로 이미지 파일을 읽어서 @ResponseBody 로 이미지 바이너리를 반환한다. UrlResource( file: + store 이미지 경로 "/로 시작" ) 현재까지는 보안에 취약하기 때문에 실무에서는 여러 체크 로직을 추가하자.
- @GetMapping("/attach/{itemId}") : 파일을 다운로드 할 때 실행한다. 파일 다운로드 시 권한 체크 같은 복잡한 상황까지 가정하고 이미지 id 를 요청했다. ( 권한 체크 후 리다이렉트 할 때 PathVariable 로 itemId 를 넘겨줘서 받음 ) 파일 다운로드시에는 고객이 업로드한 파일 이름으로 다운로드 하는게 좋다. 이때는 Content-Disposition 헤더에 attachment; filename="업로드 파일명" (규약) 값을 추가한다. 한글 이름이 깨지는 것을 방지하기 위해 UTP-8 로 인코딩 된 업로드 파일명을 헤더에 적었다.
참고: 데이터베이스에 이미지 바이너리를 전부 올리지 않는다. 파일은 스토리지에 저장하고 데이터베이스에는 실제로 파일이 저장된 경로를 저장한다. 경로도 전부를 저장하기 보다, 예제처럼 대부분의 경로는 애플리케이션에서 글로벌로 관리하고 파일명만 데이터베이스에 저장한다.
조회 뷰 ( Item-view )
</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 -->
첨부파일은 링크로 걸어두고 다운로드 가능. UploadFileName 을 출력한다.
여러 이미지 파일은 <img> 태그를 반복하여 출력. 이 때, StoreFileName 을 사용한다.