Files
football-next/app/api/upload/player-image/route.ts
2026-04-07 10:38:28 +03:30

62 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { writeFile } from "fs/promises";
import path from "path";
export async function POST(request: NextRequest) {
try {
const formData = await request.formData();
const file = formData.get("file") as File;
if (!file) {
return NextResponse.json(
{ error: "فایلی انتخاب نشده است" },
{ status: 400 }
);
}
// بررسی نوع فایل
const allowedTypes = ["image/jpeg", "image/jpg", "image/png", "image/webp"];
if (!allowedTypes.includes(file.type)) {
return NextResponse.json(
{ error: "فقط فایل‌های تصویری مجاز هستند" },
{ status: 400 }
);
}
// بررسی حجم فایل (حداکثر 5MB)
if (file.size > 5 * 1024 * 1024) {
return NextResponse.json(
{ error: "حجم فایل نباید بیشتر از 5 مگابایت باشد" },
{ status: 400 }
);
}
const bytes = await file.arrayBuffer();
const buffer = Buffer.from(bytes);
// ساخت نام یونیک برای فایل
const timestamp = Date.now();
const originalName = file.name.replace(/[^a-zA-Z0-9.-]/g, "_");
const fileName = `${timestamp}-${originalName}`;
// مسیر ذخیره فایل
const uploadDir = path.join(process.cwd(), "public", "uploads", "players");
const filePath = path.join(uploadDir, fileName);
// ذخیره فایل
await writeFile(filePath, buffer);
return NextResponse.json({
success: true,
fileName: fileName,
url: `/uploads/players/${fileName}`,
});
} catch (error) {
console.error("خطا در آپلود:", error);
return NextResponse.json(
{ error: "خطا در آپلود فایل" },
{ status: 500 }
);
}
}