feat : 업로드 조각 3개 동시 전송, 조각 진행(n/전체) 표시, 실패 시 조각 번호·원인 표시
SpecialSource Frontend (React) CD / deploy (push) Successful in 17s

https가 아닌 주소에서도 동작하도록 업로드 id 생성 대체 구현.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
headporterandClaude Opus 5.5 committed 2026-11-30 11:26:33 +09:00
1 parent 8c63189028
commit 9a8ee17075
2 files changed
+81 -23

No files matched your search

+74 -20
View File
@@ -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<number, number>(); // 조각 번호 → 지금까지 보낸 바이트
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) })) }),
});
}
+7 -3
View File
@@ -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<number | null>(null); // 업로드 중이면 보낸 비율(%)
const [uploaded, setUploaded] = useState<UploadProgress | null>(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) {
<input name="title" className={styles.wide} placeholder="비우면 영상·파일 제목으로" maxLength={500} />
</label>
<button type="submit" disabled={busy}>
{uploaded !== null ? `업로드 ${bar(uploaded, 10)}` : busy ? "요청중..." : "등록"}
{uploaded !== null
? `업로드 ${bar(uploaded.percent, 10)} · 조각 ${uploaded.done}/${uploaded.total}`
: busy
? "요청중..."
: "등록"}
</button>
</form>
<hr className={styles.rule} />