☕️ Java 47강 – 파일 다운로드 API & 이미지 미리보기

📌 요약

이번 강의에서는 업로드한 파일을 다운로드하거나 이미지로 미리보기하는 API를 만들어 봅니다.
정적 파일 서빙 + 직접 다운로드용 API도 구현해서, 프론트엔드에서 파일을 자유롭게 사용할 수 있어요!


🚀 정적 파일 서빙 설정

`application.properties`에 업로드 폴더를 정적 리소스로 등록해요. ```properties spring.web.resources.static-locations=classpath:/static/,file:./uploads/

📥 파일 다운로드 API (Content-Disposition 사용)

@GetMapping("/download/{filename}") public ResponseEntity<Resource> downloadFile(@PathVariable String filename) throws IOException { Path filePath = uploadDir.resolve(filename); Resource resource = new UrlResource(filePath.toUri()); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } 

attachment → 다운로드 창 뜸 inline → 브라우저에서 직접 보기 가능 (이미지, PDF 등)

🖼 이미지 미리보기 URL

정적 리소스를 통해 직접 접근: html 복사 편집

또는 브라우저에서 바로 열리는 API로 제공 (inline 방식): java 복사 편집 @GetMapping("/preview/{filename}") public ResponseEntity<Resource> previewFile(@PathVariable String filename) throws IOException { Path filePath = uploadDir.resolve(filename); Resource resource = new UrlResource(filePath.toUri()); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"") .body(resource); }

📂 전체 구조 요약

기능 URL 예시 설명 업로드 POST /upload 파일 업로드 다운로드 GET /download/{filename} 강제 다운로드 미리보기 GET /uploads/{filename} 브라우저 미리보기 커스텀 미리보기 GET /preview/{filename} inline 방식

✅ 한 줄 요약

파일 업로드부터 다운로드, 이미지 미리보기까지 완성하면 실무 API는 거의 끝!


👉 다음 강의: 48강 – 파일 목록 조회 & 삭제 기능 구현 (예정)

```