summaryrefslogtreecommitdiff
path: root/app/api/upload
diff options
context:
space:
mode:
authordujinkim <dujin.kim@dtsolution.co.kr>2025-07-15 10:07:09 +0000
committerdujinkim <dujin.kim@dtsolution.co.kr>2025-07-15 10:07:09 +0000
commit4eb7532f822c821fb6b69bf103bd075fefba769b (patch)
treeb4bcf6c0bf791d71569f3f35498ed256bf7cfaf3 /app/api/upload
parent660c7888d885badab7af3e96f9c16bd0172ad0f1 (diff)
(대표님) 20250715 협력사 정기평가, spreadJS, roles 서비스에 함수 추가
Diffstat (limited to 'app/api/upload')
-rw-r--r--app/api/upload/basicContract/chunk/route.ts117
1 files changed, 79 insertions, 38 deletions
diff --git a/app/api/upload/basicContract/chunk/route.ts b/app/api/upload/basicContract/chunk/route.ts
index 7100988b..e190fca4 100644
--- a/app/api/upload/basicContract/chunk/route.ts
+++ b/app/api/upload/basicContract/chunk/route.ts
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
-import { mkdir, writeFile, appendFile } from 'fs/promises';
+import { mkdir, writeFile, appendFile, readFile, rm } from 'fs/promises';
import path from 'path';
-import crypto from 'crypto';
+import { generateHashedFileName, saveBuffer } from '@/lib/file-stroage';
export async function POST(request: NextRequest) {
try {
@@ -14,58 +14,99 @@ export async function POST(request: NextRequest) {
const fileId = formData.get('fileId') as string;
if (!chunk || !filename || isNaN(chunkIndex) || isNaN(totalChunks) || !fileId) {
- return NextResponse.json({ success: false, error: '필수 매개변수가 누락되었습니다' }, { status: 400 });
+ return NextResponse.json({
+ success: false,
+ error: '필수 매개변수가 누락되었습니다'
+ }, { status: 400 });
}
-
+
// 임시 디렉토리 생성
const tempDir = path.join(process.cwd(), 'temp', 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(`📦 청크 저장 완료: ${chunkIndex + 1}/${totalChunks} (${buffer.length} bytes)`);
+
// 마지막 청크인 경우 모든 청크를 합쳐 최종 파일 생성
if (chunkIndex === totalChunks - 1) {
- const uploadDir = path.join(process.cwd(), "public", "basicContract", "template");
- await mkdir(uploadDir, { recursive: true });
+ console.log(`🔄 파일 병합 시작: ${filename}`);
- // 파일명 생성
- const timestamp = Date.now();
- const randomHash = crypto.createHash('md5')
- .update(`${filename}-${timestamp}`)
- .digest('hex')
- .substring(0, 8);
- const hashedFileName = `${timestamp}-${randomHash}${path.extname(filename)}`;
- const finalPath = path.join(uploadDir, hashedFileName);
-
- // 모든 청크 병합
- await writeFile(finalPath, Buffer.alloc(0)); // 빈 파일 생성
- for (let i = 0; i < totalChunks; i++) {
- const chunkData = await require('fs/promises').readFile(path.join(tempDir, `chunk-${i}`));
- await appendFile(finalPath, chunkData);
+ 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(`📄 병합 완료: ${filename} (총 ${totalSize} bytes)`);
+
+ // 공용 함수를 사용하여 파일 저장
+ const saveResult = await saveBuffer({
+ buffer: mergedBuffer,
+ fileName: filename,
+ directory: 'basicContract/template',
+ originalName: filename
+ });
+
+ // 임시 파일 정리 (비동기로 처리)
+ rm(tempDir, { recursive: true, force: true })
+ .then(() => console.log(`🗑️ 임시 파일 정리 완료: ${fileId}`))
+ .catch((e: unknown) => console.error('청크 정리 오류:', e));
+
+ if (saveResult.success) {
+ console.log(`✅ 최종 파일 저장 완료: ${saveResult.fileName}`);
+
+ return NextResponse.json({
+ success: true,
+ fileName: filename,
+ filePath: saveResult.publicPath,
+ hashedFileName: saveResult.fileName,
+ fileSize: totalSize
+ });
+ } else {
+ console.error('파일 저장 실패:', saveResult.error);
+ return NextResponse.json({
+ success: false,
+ error: saveResult.error || '파일 저장에 실패했습니다'
+ }, { status: 500 });
+ }
+
+ } catch (mergeError) {
+ console.error('파일 병합 오류:', mergeError);
+
+ // 오류 발생 시 임시 파일 정리
+ rm(tempDir, { recursive: true, force: true })
+ .catch((e: unknown) => console.error('임시 파일 정리 오류:', e));
+
+ return NextResponse.json({
+ success: false,
+ error: '파일 병합 중 오류가 발생했습니다'
+ }, { status: 500 });
}
-
- // 임시 파일 정리 (비동기로 처리)
- require('fs/promises').rm(tempDir, { recursive: true, force: true })
- .catch((e: unknown) => console.error('청크 정리 오류:', e));
-
- return NextResponse.json({
- success: true,
- fileName: filename,
- filePath: `/basicContract/template/${hashedFileName}`
- });
}
-
- return NextResponse.json({
- success: true,
- chunkIndex,
- message: `청크 ${chunkIndex + 1}/${totalChunks} 업로드 완료`
+
+ return NextResponse.json({
+ success: true,
+ chunkIndex,
+ message: `청크 ${chunkIndex + 1}/${totalChunks} 업로드 완료`
});
} catch (error) {
console.error('청크 업로드 오류:', error);
- return NextResponse.json({ success: false, error: '서버 오류' }, { status: 500 });
+ return NextResponse.json({
+ success: false,
+ error: '서버 오류'
+ }, { status: 500 });
}
} \ No newline at end of file