☕️ Java 48강 – 파일 목록 조회 & 삭제 기능 구현

📌 요약

이번 강의에서는 업로드된 파일들을 목록으로 조회하고 삭제할 수 있는 API를 만들어봅니다.
프론트엔드에서 파일 선택 후 삭제하거나 전체 목록을 보여주는 기능을 위해 필수예요!


📁 파일 목록 조회 API

@GetMapping("/files")
public ResponseEntity<?> listFiles() throws IOException {
    try (Stream<Path> paths = Files.list(uploadDir)) {
        List<String> fileNames = paths
            .map(Path::getFileName)
            .map(Path::toString)
            .collect(Collectors.toList());

        return ResponseEntity.ok(fileNames);
    }
}

---

🧹 파일 삭제 API

@DeleteMapping("/files/{filename}")
public ResponseEntity<?> deleteFile(@PathVariable String filename) throws IOException {
    Path filePath = uploadDir.resolve(filename);
    boolean deleted = Files.deleteIfExists(filePath);
    
    if (deleted) return ResponseEntity.ok("삭제 완료");
    else return ResponseEntity.status(404).body("파일 없음");
}

---

📦 확장 아이디어

✅ 멀티 삭제 (POST로 파일명 리스트 전달) ```java @PostMapping("/files/delete") public ResponseEntity<?> deleteMultiple(@RequestBody List<String> filenames) { List<String> failed = new ArrayList<>(); for (String name : filenames) { try { Files.deleteIfExists(uploadDir.resolve(name)); } catch (IOException e) { failed.add(name); } } return ResponseEntity.ok(Map.of( "삭제 성공", filenames.size() - failed.size(), "삭제 실패", failed )); }

🧪 결과 예시

GET /files → json 복사 편집 ["a.jpg", "b.docx", "c.txt"] DELETE /files/a.jpg → → 200 OK: "삭제 완료" → 404 Not Found: "파일 없음"

✅ 한 줄 요약

목록 + 삭제 기능까지 구현하면 파일 기반 백엔드는 실무에서도 그대로 써먹을 수 있다!


👉 다음 강의: 49강 – 백엔드 마무리: 유저별 파일 연결 및 보안 강화 (예정)

```