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
|
import { NextRequest, NextResponse } from 'next/server';
import { writeFile, mkdir } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
export async function POST(req: NextRequest) {
try {
const formData = await req.formData();
const file = formData.get('file') as File;
console.log(file)
if (!file) {
return NextResponse.json({ error: '파일이 없습니다.' }, { status: 400 });
}
// 파일 확장자 검증
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
if (!allowedTypes.includes(file.type)) {
return NextResponse.json({ error: '지원하지 않는 파일 형식입니다.' }, { status: 400 });
}
// 파일 크기 제한 (5MB)
if (file.size > 5 * 1024 * 1024) {
return NextResponse.json({ error: '파일 크기는 5MB 이하여야 합니다.' }, { status: 400 });
}
// 업로드 디렉토리 생성
const uploadDir = join(process.cwd(), 'public', 'uploads', 'richtext');
await mkdir(uploadDir, { recursive: true });
// 고유한 파일명 생성
const fileExtension = file.name.split('.').pop();
const fileName = `${randomUUID()}.${fileExtension}`;
const filePath = join(uploadDir, fileName);
// 파일 저장
const arrayBuffer = await file.arrayBuffer();
await writeFile(filePath, new Uint8Array(arrayBuffer));
// 공개 URL 반환
const fileUrl = `/uploads/richtext/${fileName}`;
return NextResponse.json({
success: true,
url: fileUrl,
message: '이미지가 성공적으로 업로드되었습니다.'
});
} catch (error) {
console.error('파일 업로드 실패:', error);
return NextResponse.json({ error: '파일 업로드에 실패했습니다.' }, { status: 500 });
}
}
|