feat : 자료실 업로드를 청크(50MB 조각) 방식으로 변경
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 53s

Cloudflare 요청 100MB 제한 때문에 /upload 를 /upload/chunk + /upload/complete 로 교체.
멈춘 업로드 임시 파일(media.dir/.uploads)은 매일 04:30에 하루 지난 것 삭제.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
headporterandClaude Opus 5.5 committed 2026-11-30 11:18:44 +09:00
1 parent d3041c0b6a
commit 048105d723
1 file changed
+80 -19
@@ -131,40 +131,81 @@ public class MediaPostController {
return ResponseEntity.ok(toResponse(post, false)); return ResponseEntity.ok(toResponse(post, false));
} }
// 업로드: 내 PC 파일을 바로 글로 등록 (봇 거치지 않음 → 바로 DONE). 원본 링크가 없어서 sourceUrl = "" // ── 업로드: 내 PC 파일을 글로 등록 (봇 거치지 않음 → 바로 DONE, 원본 링크 없음 → sourceUrl = "") ──
// 파일을 다 저장한 뒤에 글을 만들고, 저장 중 실패하면 폴더를 지움 // Cloudflare가 요청 하나를 100MB로 막아서 청크(조각) 업로드:
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) // 1) 브라우저가 파일을 조각으로 잘라 /upload/chunk 로 하나씩 → 임시 파일(media.dir/.uploads/업로드id/파일번호)에 이어 씀
public ResponseEntity<?> upload(@RequestParam("files") List<MultipartFile> files, // 2) 다 보내면 /upload/complete → 크기 확인 후 글 폴더로 옮기고 글 생성
@RequestParam(value = "title", required = false) String title, // 다 못 보내고 멈춘 임시 파일은 cleanUploads가 하루 뒤 지움
@RequestParam(value = "category", required = false) String category,
Principal principal) throws IOException { private static final java.util.regex.Pattern UPLOAD_ID = java.util.regex.Pattern.compile("[0-9a-f-]{36}"); // 브라우저 crypto.randomUUID()
files = files.stream().filter(f -> !f.isEmpty()).toList();
if (files.isEmpty()) return ResponseEntity.badRequest().body(Map.of("error", "파일을 선택하세요")); public record UploadFile(String name, long size) {}
public record UploadCompleteRequest(String uploadId, String title, String category, List<UploadFile> files) {}
private Path uploadDir(String uploadId) {
return mediaDir.resolve(".uploads").resolve(uploadId);
}
// 조각 하나. offset = 이 조각이 파일의 몇 바이트째부터인지
// 같은 조각을 다시 보내도(응답만 못 받은 재시도) offset부터 덮어써서 두 번 붙지 않음
@PostMapping(value = "/upload/chunk", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> uploadChunk(@RequestParam String uploadId, @RequestParam int fileIndex,
@RequestParam long offset, @RequestParam MultipartFile chunk) throws IOException {
if (!UPLOAD_ID.matcher(uploadId).matches() || fileIndex < 0 || fileIndex >= 1000 || offset < 0) {
return ResponseEntity.badRequest().body(Map.of("error", "잘못된 업로드 요청입니다"));
}
Path part = uploadDir(uploadId).resolve(String.valueOf(fileIndex));
Files.createDirectories(part.getParent());
long size = Files.exists(part) ? Files.size(part) : 0;
if (size < offset) { // 앞 조각이 빠짐
return ResponseEntity.status(409).body(Map.of("error", "업로드 조각 순서가 맞지 않습니다", "size", size));
}
try (java.nio.channels.FileChannel ch = java.nio.channels.FileChannel.open(part,
java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.WRITE);
java.io.InputStream in = chunk.getInputStream()) {
ch.truncate(offset);
ch.position(offset);
in.transferTo(java.nio.channels.Channels.newOutputStream(ch));
}
return ResponseEntity.noContent().build();
}
// 마무리: 파일마다 받은 크기가 맞는지 확인 → 글 폴더로 옮기고 글 생성
@PostMapping("/upload/complete")
public ResponseEntity<?> uploadComplete(@RequestBody UploadCompleteRequest request, Principal principal) throws IOException {
if (request.uploadId() == null || !UPLOAD_ID.matcher(request.uploadId()).matches()
|| request.files() == null || request.files().isEmpty() || request.files().size() > 1000) {
return ResponseEntity.badRequest().body(Map.of("error", "파일을 선택하세요"));
}
Path temp = uploadDir(request.uploadId());
for (int i = 0; i < request.files().size(); i++) {
Path part = temp.resolve(String.valueOf(i));
if (!Files.exists(part) || Files.size(part) != request.files().get(i).size()) {
return ResponseEntity.badRequest().body(Map.of("error", "업로드가 끝나지 않은 파일이 있습니다: " + request.files().get(i).name()));
}
}
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
String folder = now.format(FOLDER_DATE) + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12); String folder = now.format(FOLDER_DATE) + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
Path dir = mediaDir.resolve(folder); Path dir = mediaDir.resolve(folder);
Files.createDirectories(dir); Files.createDirectories(dir);
try { for (int i = 0; i < request.files().size(); i++) {
for (int i = 0; i < files.size(); i++) {
// 경로 조각·윈도우 금지 문자 제거. 숨김(.)·빈 이름이면 번호 이름, 같은 이름이 있으면 앞에 번호 // 경로 조각·윈도우 금지 문자 제거. 숨김(.)·빈 이름이면 번호 이름, 같은 이름이 있으면 앞에 번호
String name = Paths.get(String.valueOf(files.get(i).getOriginalFilename())).getFileName().toString() String name = Paths.get(String.valueOf(request.files().get(i).name())).getFileName().toString()
.replaceAll("[\\\\/:*?\"<>|]", "_").trim(); .replaceAll("[\\\\/:*?\"<>|]", "_").trim();
if (name.isEmpty() || name.startsWith(".") || name.equals("null")) name = "file" + (i + 1) + name; if (name.isEmpty() || name.startsWith(".") || name.equals("null")) name = "file" + (i + 1) + name;
if (Files.exists(dir.resolve(name))) name = (i + 1) + "_" + name; if (Files.exists(dir.resolve(name))) name = (i + 1) + "_" + name;
files.get(i).transferTo(dir.resolve(name)); Files.move(temp.resolve(String.valueOf(i)), dir.resolve(name)); // 같은 디스크라 복사 없이 이동
}
} catch (IOException e) {
try (Stream<Path> walk = Files.walk(dir)) {
for (Path p : walk.sorted(Comparator.reverseOrder()).toList()) Files.deleteIfExists(p);
}
return ResponseEntity.status(500).body(Map.of("error", "파일 저장에 실패했습니다"));
} }
deleteTree(temp);
// 제목을 비우면 첫 파일 이름 (확장자 빼고) // 제목을 비우면 첫 파일 이름 (확장자 빼고)
String title = request.title();
String t = title == null || title.isBlank() String t = title == null || title.isBlank()
? listFiles(folder).stream().findFirst().map(p -> p.getFileName().toString().replaceFirst("\\.[^.]+$", "")).orElse("업로드") ? listFiles(folder).stream().findFirst().map(p -> p.getFileName().toString().replaceFirst("\\.[^.]+$", "")).orElse("업로드")
: title.trim(); : title.trim();
String category = request.category();
MediaPost post = repository.save(MediaPost.builder() MediaPost post = repository.save(MediaPost.builder()
.title(t.length() > 500 ? t.substring(0, 500) : t) .title(t.length() > 500 ? t.substring(0, 500) : t)
.sourceUrl("") .sourceUrl("")
@@ -177,6 +218,26 @@ public class MediaPostController {
return ResponseEntity.ok(toResponse(post, false)); return ResponseEntity.ok(toResponse(post, false));
} }
// 매일 새벽 4시 30분: 하루 넘게 손대지 않은 업로드 임시 폴더 삭제 (창을 닫는 등으로 멈춘 업로드)
@org.springframework.scheduling.annotation.Scheduled(cron = "0 30 4 * * *")
public void cleanUploads() throws IOException {
Path root = mediaDir.resolve(".uploads");
if (!Files.isDirectory(root)) return;
java.nio.file.attribute.FileTime limit = java.nio.file.attribute.FileTime.from(java.time.Instant.now().minus(java.time.Duration.ofDays(1)));
try (Stream<Path> dirs = Files.list(root)) {
for (Path d : dirs.toList()) {
if (Files.getLastModifiedTime(d).compareTo(limit) < 0) deleteTree(d);
}
}
}
private static void deleteTree(Path dir) throws IOException {
if (!Files.exists(dir)) return;
try (Stream<Path> walk = Files.walk(dir)) {
for (Path p : walk.sorted(Comparator.reverseOrder()).toList()) Files.deleteIfExists(p); // 안쪽 파일부터
}
}
// 목록 + 검색. 조건은 준 것만 적용 // 목록 + 검색. 조건은 준 것만 적용
// category: 없으면 전체, 빈 문자열("")이면 미분류 // category: 없으면 전체, 빈 문자열("")이면 미분류
// q: 제목에 포함 (대소문자 무시), from/to: 등록일 범위 (yyyy-MM-dd, to 당일 포함) // q: 제목에 포함 (대소문자 무시), from/to: 등록일 범위 (yyyy-MM-dd, to 당일 포함)