import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; import { writeFile, mkdir } from 'fs/promises'; import path from 'path'; // POST - 上传 PSD 文件到本地 export async function POST(request: NextRequest) { try { const session = await getServerSession(authOptions); if (!session) { return NextResponse.json({ error: '请先登录' }, { status: 401 }); } const formData = await request.formData(); const file = formData.get('file') as File; const materialId = formData.get('materialId') as string; if (!file || !materialId) { return NextResponse.json({ error: '缺少文件或素材ID' }, { status: 400 }); } // 生成本地存储路径 const timestamp = Date.now(); const ext = file.name.split('.').pop(); const fileName = `psd-${timestamp}.${ext}`; const uploadDir = path.join(process.cwd(), 'uploads', 'product-package', materialId, 'psd'); const filePath = path.join(uploadDir, fileName); // 确保目录存在 await mkdir(uploadDir, { recursive: true }); // 保存文件 const buffer = Buffer.from(await file.arrayBuffer()); await writeFile(filePath, buffer); // 返回相对路径 const relativePath = path.join('uploads', 'product-package', materialId, 'psd', fileName); return NextResponse.json({ path: relativePath }); } catch (error) { console.error('[PSD Upload] Error:', error); return NextResponse.json( { error: '上传失败: ' + (error instanceof Error ? error.message : '未知错误') }, { status: 500 } ); } }