mirror of
https://github.com/headporter81/ss-front-react.git
synced 2026-12-06 07:41:11 +09:00
feat : 자료실 업로드를 50MB 조각으로 나눠 전송 (조각별 3회 재시도), 학습노트 13 추가
SpecialSource Frontend (React) CD / deploy (push) Successful in 15s
SpecialSource Frontend (React) CD / deploy (push) Successful in 15s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
de5ea95de1
commit
8c63189028
3 files changed
+67
-12
No files matched your search
+3
-3
@@ -5,9 +5,9 @@ server {
|
||||
|
||||
# 같은 도메인의 /api 요청을 NAS 백엔드(18080)로 전달 → 브라우저는 CORS 없이 호출
|
||||
location /api/ {
|
||||
# 자료실 파일 업로드: nginx 기본 1MB 제한 → 백엔드(multipart 5GB)와 맞춤
|
||||
# 버퍼링 끔: 큰 파일을 nginx 디스크에 다 받은 뒤 넘기지 않고 바로 백엔드로 흘려보냄
|
||||
client_max_body_size 5g;
|
||||
# 자료실 파일 업로드: nginx 기본 1MB 제한 → 업로드 조각(50MB)이 지나가도록 100MB
|
||||
# 버퍼링 끔: 조각을 nginx 디스크에 다 받은 뒤 넘기지 않고 바로 백엔드로 흘려보냄
|
||||
client_max_body_size 100m;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_send_timeout 600s;
|
||||
|
||||
+44
-9
@@ -67,24 +67,22 @@ export const createMediaPost = (token: string, url: string, title: string, categ
|
||||
body: JSON.stringify({ url, title, category }),
|
||||
});
|
||||
|
||||
/** 조각 크기: Cloudflare가 요청 하나를 100MB로 막아서 여유 있게 50MB */
|
||||
const CHUNK_SIZE = 50 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* 내 PC 파일 업로드 → 바로 완료된 글로 등록. onProgress: 보낸 비율(0~100)
|
||||
* 조각 하나 보내기. onSent: 이 조각에서 보낸 바이트 (진행률용)
|
||||
* fetch는 업로드 진행률을 알려주지 않아서 XMLHttpRequest 사용
|
||||
*/
|
||||
export const uploadMediaFiles = (token: string, files: File[], title: string, category: string, onProgress: (percent: number) => void) =>
|
||||
const sendChunk = (token: string, body: FormData, onSent: (bytes: number) => void) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
const body = new FormData();
|
||||
files.forEach((f) => body.append("files", f));
|
||||
body.append("title", title);
|
||||
body.append("category", category);
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("POST", `${API_URL}/api/media-posts/upload`);
|
||||
xhr.open("POST", `${API_URL}/api/media-posts/upload/chunk`);
|
||||
xhr.setRequestHeader("Authorization", `Bearer ${token}`);
|
||||
xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(Math.floor((e.loaded / e.total) * 100));
|
||||
xhr.upload.onprogress = (e) => onSent(e.loaded);
|
||||
xhr.onerror = () => reject(new Error("※ 업로드 중 연결이 끊어졌습니다."));
|
||||
xhr.onload = () => {
|
||||
if (xhr.status === 401 || xhr.status === 403) return reject(new AuthError("※ 로그인이 만료되었습니다. 다시 로그인하세요."));
|
||||
if (xhr.status === 413) return reject(new Error("※ 파일이 너무 큽니다."));
|
||||
if (xhr.status < 200 || xhr.status >= 300) {
|
||||
let reason: string | undefined;
|
||||
try {
|
||||
@@ -97,6 +95,43 @@ export const uploadMediaFiles = (token: string, files: File[], title: string, ca
|
||||
xhr.send(body);
|
||||
});
|
||||
|
||||
/**
|
||||
* 내 PC 파일 업로드 → 바로 완료된 글로 등록. onProgress: 보낸 비율(0~100)
|
||||
* 파일을 50MB 조각으로 잘라 하나씩 보내고(실패한 조각은 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); // 잘라도 파일 전체를 메모리에 올리지 않음
|
||||
const body = new FormData();
|
||||
body.append("uploadId", uploadId);
|
||||
body.append("fileIndex", String(i));
|
||||
body.append("offset", String(offset));
|
||||
body.append("chunk", piece, file.name);
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
await sendChunk(token, body, (sent) => onProgress(Math.min(100, Math.floor(((done + sent) / total) * 100))) /* sent엔 포장 바이트도 섞여 살짝 넘칠 수 있음 */);
|
||||
break;
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError || attempt >= 3) throw e;
|
||||
}
|
||||
}
|
||||
done += piece.size;
|
||||
if (file.size === 0) break;
|
||||
}
|
||||
}
|
||||
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 })) }),
|
||||
});
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 30;
|
||||
|
||||
/**
|
||||
|
||||
@@ -280,3 +280,23 @@ yt-dlp, ffmpeg, 쿠키 인증, 콜백(callback), 비동기 작업, 공유 볼륨
|
||||
|
||||
### 키워드
|
||||
Graph API, 액세스 토큰, OAuth, 비즈니스 계정, 앱 심사, Business Discovery
|
||||
|
||||
---
|
||||
|
||||
## 13. 100MB 넘는 파일은 어떻게 올릴까? (청크 업로드)
|
||||
|
||||
**질문**: 100MB 넘는 파일 업로드가 실패하면, 멀티파트로 나눠 올려서 서버에서 합치는 방식으로 하나?
|
||||
|
||||
**요약**: 맞다. 정확한 이름은 **청크(조각) 업로드**다. 브라우저가 파일을 50MB 같은 조각으로 잘라 한 조각씩 보내고, 서버가 받은 순서대로 이어 붙여 원래 파일로 만든다. 요청 하나하나가 100MB보다 작아서 Cloudflare 제한에 걸리지 않는다.
|
||||
|
||||
### 핵심 내용
|
||||
- "멀티파트(multipart/form-data)"는 요청 하나에 파일·글자를 함께 담는 **포장 형식**이다. 지금 업로드도 이미 멀티파트다. 파일을 여러 요청으로 **나누는 것**은 청크 업로드라고 부른다
|
||||
- 브라우저: `file.slice(시작, 끝)`으로 파일을 자른다. 파일 전체를 메모리에 올리지 않아서 큰 파일도 괜찮다
|
||||
- 서버: 업로드마다 임시 id를 주고, 조각이 오면 임시 파일 뒤에 이어 쓴다. 마지막 조각이 오면 자료실 폴더로 옮기고 글을 만든다
|
||||
- 조각 번호를 같이 보내야 순서가 꼬이거나 같은 조각이 두 번 붙는 일을 막을 수 있다
|
||||
- 장점: 실패한 조각만 다시 보내면 된다 (이어 올리기 가능)
|
||||
- 주의: 중간에 멈춘 업로드의 임시 파일은 서버가 주기적으로 지워야 디스크가 차지 않는다
|
||||
- 다른 방법: 업로드 전용 주소만 Cloudflare를 거치지 않게(DNS only) 하면 코드는 그대로지만 NAS의 실제 IP가 드러난다
|
||||
|
||||
### 키워드
|
||||
청크 업로드, multipart/form-data, File.slice, Cloudflare 100MB 제한, 이어 올리기, 임시 파일 정리
|
||||
Reference in new issue
Block a user