From 9a8ee1707507a0ccba08fd2185c6baf7e828c813 Mon Sep 17 00:00:00 2001 From: "sungjin.choi" Date: Mon, 30 Nov 2026 11:26:33 +0900 Subject: [PATCH] =?UTF-8?q?feat=20:=20=EC=97=85=EB=A1=9C=EB=93=9C=20?= =?UTF-8?q?=EC=A1=B0=EA=B0=81=203=EA=B0=9C=20=EB=8F=99=EC=8B=9C=20?= =?UTF-8?q?=EC=A0=84=EC=86=A1,=20=EC=A1=B0=EA=B0=81=20=EC=A7=84=ED=96=89(n?= =?UTF-8?q?/=EC=A0=84=EC=B2=B4)=20=ED=91=9C=EC=8B=9C,=20=EC=8B=A4=ED=8C=A8?= =?UTF-8?q?=20=EC=8B=9C=20=EC=A1=B0=EA=B0=81=20=EB=B2=88=ED=98=B8=C2=B7?= =?UTF-8?q?=EC=9B=90=EC=9D=B8=20=ED=91=9C=EC=8B=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https가 아닌 주소에서도 동작하도록 업로드 id 생성 대체 구현. Co-Authored-By: Claude Opus 5.5 --- src/features/bbs/api.ts | 94 ++++++++++++++++++----- src/features/bbs/components/MediaList.tsx | 10 ++- 2 files changed, 81 insertions(+), 23 deletions(-) diff --git a/src/features/bbs/api.ts b/src/features/bbs/api.ts index c5337e8..0d53034 100644 --- a/src/features/bbs/api.ts +++ b/src/features/bbs/api.ts @@ -80,7 +80,7 @@ const sendChunk = (token: string, body: FormData, onSent: (bytes: number) => voi xhr.open("POST", `${API_URL}/api/media-posts/upload/chunk`); xhr.setRequestHeader("Authorization", `Bearer ${token}`); xhr.upload.onprogress = (e) => onSent(e.loaded); - xhr.onerror = () => reject(new Error("※ 업로드 중 연결이 끊어졌습니다.")); + xhr.onerror = () => reject(new Error("※ 연결이 끊어졌습니다 (네트워크 또는 중간 서버가 요청을 막음)")); xhr.onload = () => { if (xhr.status === 401 || xhr.status === 403) return reject(new AuthError("※ 로그인이 만료되었습니다. 다시 로그인하세요.")); if (xhr.status < 200 || xhr.status >= 300) { @@ -95,40 +95,94 @@ const sendChunk = (token: string, body: FormData, onSent: (bytes: number) => voi xhr.send(body); }); +/** 동시에 보낼 조각 수. 브라우저는 한 사이트에 동시 연결을 6개 정도까지 열어서 그 안에서 여유 있게 */ +const PARALLEL = 3; + +/** 업로드 진행 상황: percent = 보낸 바이트 비율, done/total = 다 보낸 조각 수 / 전체 조각 수 */ +export interface UploadProgress { + percent: number; + done: number; + total: number; +} + +/** crypto.randomUUID는 https에서만 있음 → http(내부망 주소)로 접속해도 되도록 직접 만듦 */ +const uuid = () => + crypto.randomUUID?.() ?? + "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => + (Number(c) ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (Number(c) / 4)))).toString(16), + ); + /** - * 내 PC 파일 업로드 → 바로 완료된 글로 등록. onProgress: 보낸 비율(0~100) - * 파일을 50MB 조각으로 잘라 하나씩 보내고(실패한 조각은 3번까지 다시), 다 보내면 서버가 글을 만듦 + * 내 PC 파일 업로드 → 바로 완료된 글로 등록 + * 파일을 50MB 조각으로 잘라 PARALLEL개씩 동시에 보내고(실패한 조각은 3번까지 다시), 다 보내면 서버가 글을 만듦 */ -export async function uploadMediaFiles(token: string, files: File[], title: string, category: string, onProgress: (percent: number) => void) { - const uploadId = crypto.randomUUID(); // 이 업로드의 조각들을 서버가 한곳에 모으는 이름표 - const total = files.reduce((sum, f) => sum + f.size, 0) || 1; - let done = 0; // 다 보낸 조각들의 바이트 - for (let i = 0; i < files.length; i++) { - const file = files[i]; - // 0바이트 파일도 빈 조각 하나는 보내야 서버에 파일이 생김 - for (let offset = 0; offset < file.size || offset === 0; offset += CHUNK_SIZE) { - const piece = file.slice(offset, offset + CHUNK_SIZE); // 잘라도 파일 전체를 메모리에 올리지 않음 +export async function uploadMediaFiles( + token: string, + files: File[], + title: string, + category: string, + onProgress: (p: UploadProgress) => void, +) { + const uploadId = uuid(); // 이 업로드의 조각들을 서버가 한곳에 모으는 이름표 + // 보낼 조각 목록. 0바이트 파일도 빈 조각 하나는 보내야 서버에 파일이 생김 + const chunksOf = (f: File) => Math.max(1, Math.ceil(f.size / CHUNK_SIZE)); + const tasks = files.flatMap((file, fileIndex) => + Array.from({ length: chunksOf(file) }, (_, chunkIndex) => ({ file, fileIndex, chunkIndex, offset: chunkIndex * CHUNK_SIZE })), + ); + const totalBytes = files.reduce((sum, f) => sum + f.size, 0) || 1; + const sent = new Map(); // 조각 번호 → 지금까지 보낸 바이트 + let done = 0; + const report = () => { + const bytes = [...sent.values()].reduce((a, b) => a + b, 0); + // sent엔 포장 바이트도 섞여 살짝 넘칠 수 있음 + onProgress({ percent: Math.min(100, Math.floor((bytes / totalBytes) * 100)), done, total: tasks.length }); + }; + report(); + + let next = 0; // 다음에 보낼 조각 (자바스크립트는 한 줄씩 실행돼서 next++가 겹치지 않음) + let failed = false; + // 일꾼 PARALLEL개가 목록에서 조각을 하나씩 가져가 보냄. 하나가 끝나면 바로 다음 조각 + const worker = async () => { + while (!failed && next < tasks.length) { + const n = next++; + const t = tasks[n]; + const piece = t.file.slice(t.offset, t.offset + CHUNK_SIZE); // 잘라도 파일 전체를 메모리에 올리지 않음 const body = new FormData(); body.append("uploadId", uploadId); - body.append("fileIndex", String(i)); - body.append("offset", String(offset)); - body.append("chunk", piece, file.name); + body.append("fileIndex", String(t.fileIndex)); + body.append("chunkIndex", String(t.chunkIndex)); + body.append("offset", String(t.offset)); + body.append("chunk", piece, t.file.name); for (let attempt = 1; ; attempt++) { try { - await sendChunk(token, body, (sent) => onProgress(Math.min(100, Math.floor(((done + sent) / total) * 100))) /* sent엔 포장 바이트도 섞여 살짝 넘칠 수 있음 */); + await sendChunk(token, body, (bytes) => { + sent.set(n, Math.min(bytes, piece.size)); + report(); + }); break; } catch (e) { - if (e instanceof AuthError || attempt >= 3) throw e; + if (e instanceof AuthError) throw e; + if (attempt >= 3) { + const where = `조각 ${n + 1}/${tasks.length}${files.length > 1 ? ` (${t.file.name})` : ""}`; + throw new Error(`※ ${where} 업로드 실패 — ${e instanceof Error ? e.message.replace(/^※\s*/, "") : e}`); + } } } - done += piece.size; - if (file.size === 0) break; + sent.set(n, piece.size); + done++; + report(); } + }; + try { + await Promise.all(Array.from({ length: Math.min(PARALLEL, tasks.length) }, worker)); + } catch (e) { + failed = true; // 나머지 일꾼도 멈춤 + throw e; } await call("/api/media-posts/upload/complete", token, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ uploadId, title, category, files: files.map((f) => ({ name: f.name, size: f.size })) }), + body: JSON.stringify({ uploadId, title, category, files: files.map((f) => ({ name: f.name, size: f.size, chunks: chunksOf(f) })) }), }); } diff --git a/src/features/bbs/components/MediaList.tsx b/src/features/bbs/components/MediaList.tsx index a63d833..6d6e658 100644 --- a/src/features/bbs/components/MediaList.tsx +++ b/src/features/bbs/components/MediaList.tsx @@ -1,5 +1,5 @@ import { useState, type FormEvent } from "react"; -import { createMediaPost, uploadMediaFiles } from "../api"; +import { createMediaPost, uploadMediaFiles, type UploadProgress } from "../api"; import type { MediaPost, MediaQuery } from "../types"; import DatePicker from "./DatePicker"; import { MoreSentinel } from "./PostList"; @@ -33,7 +33,7 @@ const EMPTY_SEARCH = { q: "", from: "", to: "" }; export default function MediaList(props: Props) { const { posts, total, last, onMore, categories, query, token, onSelect, onQuery, onCreated, onError } = props; const [busy, setBusy] = useState(false); - const [uploaded, setUploaded] = useState(null); // 업로드 중이면 보낸 비율(%) + const [uploaded, setUploaded] = useState(null); // 업로드 중이면 진행 상황 const tabs = [{ key: null, name: "전체" }, ...categories.map((c) => ({ key: c, name: c })), { key: "", name: "미분류" }]; const searching = query.q || query.from || query.to; @@ -115,7 +115,11 @@ export default function MediaList(props: Props) {