Spring boot - 파일 다운로드 서비스 구현하기

목차

파일 다운로드

서버에 저장된 파일을 다운 받기 위해서는 Response 해더에 Content-Disposition 정보가 필요합니다.

String contentDisposition = "attachment; filename=\"" + encodedUploadFileName + "\"";

Resource 객체로 업로드된 파일을 전송한다. UrlResource 객체를 이용해 특정 경로에 저장된 Resource 를 가져온 후 ResponseEntity 의 Body에 넣어서 반환한다.

@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);
}

전체 코드


@Slf4j
@Controller
@RequiredArgsConstructor
public class ItemController {

private final ItemRepository itemRepository;
private final FileStore fileStore;

@GetMapping("/items/new")
public String newItem(@ModelAttribute ItemForm form) {
return "item-form";
}

@PostMapping("/items/new")
public 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 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);
}

}
Share