1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
|
// app/api/upload/project-doc-template/chunk/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { mkdir, writeFile, readFile, rm } from 'fs/promises';
import path from 'path';
import { saveBuffer, saveDRMFile } from '@/lib/file-stroage';
import { decryptWithServerAction } from '@/components/drm/drmUtils';
// 허용된 파일 타입
const ALLOWED_MIME_TYPES = [
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
];
export async function POST(request: NextRequest) {
try {
const formData = await request.formData();
const chunk = formData.get('chunk') as File;
const filename = formData.get('filename') as string;
const chunkIndex = parseInt(formData.get('chunkIndex') as string);
const totalChunks = parseInt(formData.get('totalChunks') as string);
const fileId = formData.get('fileId') as string;
// 필수 매개변수 검증
if (!chunk || !filename || isNaN(chunkIndex) || isNaN(totalChunks) || !fileId) {
return NextResponse.json({
success: false,
error: '필수 매개변수가 누락되었습니다'
}, { status: 400 });
}
// 파일 확장자 검증
const fileExtension = filename.toLowerCase().split('.').pop();
if (!fileExtension || !['doc', 'docx'].includes(fileExtension)) {
return NextResponse.json({
success: false,
error: '워드 파일(.doc, .docx)만 업로드 가능합니다'
}, { status: 400 });
}
// 임시 디렉토리 생성
const tempDir = path.join(process.cwd(), 'temp', 'project-doc-templates', fileId);
await mkdir(tempDir, { recursive: true });
// 청크 파일 저장
const chunkPath = path.join(tempDir, `chunk-${chunkIndex}`);
const buffer = Buffer.from(await chunk.arrayBuffer());
await writeFile(chunkPath, buffer);
console.log(`📄 [ProjectDocTemplate] 청크 저장: ${chunkIndex + 1}/${totalChunks} - ${filename}`);
// 마지막 청크인 경우 모든 청크를 합쳐 최종 파일 생성
if (chunkIndex === totalChunks - 1) {
console.log(`🔄 [ProjectDocTemplate] 파일 병합 시작: ${filename}`);
try {
// 모든 청크를 순서대로 읽어서 병합
const chunks: Buffer[] = [];
let totalSize = 0;
for (let i = 0; i < totalChunks; i++) {
const chunkData = await readFile(path.join(tempDir, `chunk-${i}`));
chunks.push(chunkData);
totalSize += chunkData.length;
}
// 모든 청크를 하나의 Buffer로 병합
const mergedBuffer = Buffer.concat(chunks, totalSize);
console.log(`✅ [ProjectDocTemplate] 병합 완료: ${filename} (${totalSize} bytes)`);
// MIME 타입 결정
const mimeType = fileExtension === 'docx'
? 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
: 'application/msword';
// 환경에 따른 저장 방식 선택
const isProduction = process.env.NODE_ENV === 'production';
let saveResult;
if (isProduction) {
// Production: DRM 파일 처리
console.log(`🔐 [ProjectDocTemplate] Production - DRM 처리: ${filename}`);
const mergedFile = new File([mergedBuffer], filename, {
type: mimeType,
lastModified: Date.now(),
});
saveResult = await saveDRMFile(
mergedFile,
decryptWithServerAction,
'project-doc-templates', // 프로젝트 문서 템플릿 전용 디렉토리
);
} else {
// Development: 일반 파일 저장
console.log(`🛠️ [ProjectDocTemplate] Development - 일반 저장: ${filename}`);
saveResult = await saveBuffer({
buffer: mergedBuffer,
fileName: filename,
directory: 'project-doc-templates', // 프로젝트 문서 템플릿 전용 디렉토리
originalName: filename
});
}
// 임시 파일 정리 (비동기로 처리)
rm(tempDir, { recursive: true, force: true })
.then(() => console.log(`🗑️ [ProjectDocTemplate] 임시 파일 정리 완료: ${fileId}`))
.catch((e: unknown) => console.error('[ProjectDocTemplate] 청크 정리 오류:', e));
if (saveResult.success) {
const envPrefix = isProduction ? '🔐' : '🛠️';
console.log(`${envPrefix} [ProjectDocTemplate] 파일 저장 완료: ${saveResult.fileName}`);
return NextResponse.json({
success: true,
fileName: filename,
filePath: saveResult.publicPath,
hashedFileName: saveResult.fileName,
fileSize: totalSize,
mimeType,
environment: isProduction ? 'production' : 'development',
processingType: isProduction ? 'DRM' : 'standard',
templateType: 'project-doc-template'
});
} else {
console.error(`[ProjectDocTemplate] 파일 저장 실패:`, saveResult.error);
return NextResponse.json({
success: false,
error: saveResult.error || '파일 저장에 실패했습니다',
environment: isProduction ? 'production' : 'development'
}, { status: 500 });
}
} catch (mergeError) {
console.error('[ProjectDocTemplate] 파일 병합 오류:', mergeError);
// 오류 발생 시 임시 파일 정리
rm(tempDir, { recursive: true, force: true })
.catch((e: unknown) => console.error('[ProjectDocTemplate] 임시 파일 정리 오류:', e));
return NextResponse.json({
success: false,
error: '파일 병합 중 오류가 발생했습니다'
}, { status: 500 });
}
}
// 중간 청크 업로드 성공 응답
return NextResponse.json({
success: true,
chunkIndex,
message: `청크 ${chunkIndex + 1}/${totalChunks} 업로드 완료`
});
} catch (error) {
console.error('[ProjectDocTemplate] 청크 업로드 오류:', error);
const errorMessage = error instanceof Error ? error.message : '서버 오류가 발생했습니다';
return NextResponse.json({
success: false,
error: errorMessage
}, { status: 500 });
}
}
// OPTIONS 요청 처리 (CORS)
export async function OPTIONS(request: NextRequest) {
return new NextResponse(null, {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
},
});
}
|