diff --git a/src/main/java/company/specialsource/controller/MediaPostController.java b/src/main/java/company/specialsource/controller/MediaPostController.java index 7c8d3cd..758d1a4 100644 --- a/src/main/java/company/specialsource/controller/MediaPostController.java +++ b/src/main/java/company/specialsource/controller/MediaPostController.java @@ -133,13 +133,14 @@ public class MediaPostController { // ── 업로드: 내 PC 파일을 글로 등록 (봇 거치지 않음 → 바로 DONE, 원본 링크 없음 → sourceUrl = "") ── // Cloudflare가 요청 하나를 100MB로 막아서 청크(조각) 업로드: - // 1) 브라우저가 파일을 조각으로 잘라 /upload/chunk 로 하나씩 → 임시 파일(media.dir/.uploads/업로드id/파일번호)에 이어 씀 - // 2) 다 보내면 /upload/complete → 크기 확인 후 글 폴더로 옮기고 글 생성 + // 1) 브라우저가 파일을 조각으로 잘라 /upload/chunk 로 여러 개 동시에 → 임시 파일(media.dir/.uploads/업로드id/파일번호)의 + // 제자리(offset)에 바로 쓰고, 받은 조각마다 표시 파일("파일번호.조각번호.ok")을 남김 + // 2) 다 보내면 /upload/complete → 모든 조각 표시·크기 확인 후 글 폴더로 옮기고 글 생성 // 다 못 보내고 멈춘 임시 파일은 cleanUploads가 하루 뒤 지움 - private static final java.util.regex.Pattern UPLOAD_ID = java.util.regex.Pattern.compile("[0-9a-f-]{36}"); // 브라우저 crypto.randomUUID() + private static final java.util.regex.Pattern UPLOAD_ID = java.util.regex.Pattern.compile("[0-9a-f-]{36}"); // 브라우저가 만든 UUID - public record UploadFile(String name, long size) {} + public record UploadFile(String name, long size, int chunks) {} // chunks: 이 파일을 자른 조각 수 public record UploadCompleteRequest(String uploadId, String title, String category, List files) {} @@ -147,27 +148,26 @@ public class MediaPostController { return mediaDir.resolve(".uploads").resolve(uploadId); } - // 조각 하나. offset = 이 조각이 파일의 몇 바이트째부터인지 - // 같은 조각을 다시 보내도(응답만 못 받은 재시도) offset부터 덮어써서 두 번 붙지 않음 + // 조각 하나. offset = 이 조각이 파일의 몇 바이트째부터인지 → 그 자리에 바로 씀 (순서 상관없이 동시에 와도 됨) + // 같은 조각을 다시 보내도(응답만 못 받은 재시도) 같은 자리를 덮어써서 두 번 붙지 않음 @PostMapping(value = "/upload/chunk", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity uploadChunk(@RequestParam String uploadId, @RequestParam int fileIndex, + public ResponseEntity uploadChunk(@RequestParam String uploadId, @RequestParam int fileIndex, @RequestParam int chunkIndex, @RequestParam long offset, @RequestParam MultipartFile chunk) throws IOException { - if (!UPLOAD_ID.matcher(uploadId).matches() || fileIndex < 0 || fileIndex >= 1000 || offset < 0) { + if (!UPLOAD_ID.matcher(uploadId).matches() || fileIndex < 0 || fileIndex >= 1000 + || chunkIndex < 0 || chunkIndex >= 100_000 || 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)); - } + Path temp = uploadDir(uploadId); + Files.createDirectories(temp); + Path part = temp.resolve(String.valueOf(fileIndex)); 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)); } + // 다 쓴 뒤에 표시 → 표시가 있으면 그 조각은 확실히 들어감 + Files.write(temp.resolve(fileIndex + "." + chunkIndex + ".ok"), new byte[0]); return ResponseEntity.noContent().build(); } @@ -180,9 +180,13 @@ public class MediaPostController { } Path temp = uploadDir(request.uploadId()); for (int i = 0; i < request.files().size(); i++) { + UploadFile f = request.files().get(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())); + // 동시에 쓰면 중간 조각이 빠져도 크기는 맞을 수 있음 → 조각 표시까지 모두 확인 + boolean ok = Files.exists(part) && Files.size(part) == f.size() && f.chunks() > 0; + for (int c = 0; ok && c < f.chunks(); c++) ok = Files.exists(temp.resolve(i + "." + c + ".ok")); + if (!ok) { + return ResponseEntity.badRequest().body(Map.of("error", "업로드가 끝나지 않은 파일이 있습니다: " + f.name())); } }