может кому нибудь пригодится мое решение:
файл api/upload/route.ts
import mime from "mime";
import { join } from "path";
import { stat, mkdir, writeFile } from "fs/promises";
import { NextRequest, NextResponse } from "next/server";
export async function POST(request: NextRequest) {
const formData = await request.formData();
const file = formData.get("file") as Blob | null;
if (!file) {
return NextResponse.json(
{ error: "File blob is required." },
{ status: 400 }
);
}
const folder = formData.get("folder") as string;
const relativeUploadDir = `/portfolio/${folder}`;
const uploadDir = join(process.cwd(), "public/", relativeUploadDir);
try {
await stat(uploadDir);
} catch (e: any) {
if (e.code === "ENOENT") {
await mkdir(uploadDir, { recursive: true });
} else {
console.error(
"Ошибка при попытке создать каталог при загрузке файла\n",
e
);
return NextResponse.json(
{ error: "Что-то пошло не так." },
{ status: 500 }
);
}
}
try {
const folderArray = [];
const formDataEntryValues = Array.from(formData.values()) as [];
for (const formDataEntryValue of formDataEntryValues) {
if (
typeof formDataEntryValue === "object" &&
"arrayBuffer" in formDataEntryValue
) {
const file = formDataEntryValue as unknown as Blob;
const buffer = Buffer.from(await file.arrayBuffer());
await writeFile(`${uploadDir}/${file.name}`, buffer);
folderArray.push(`${relativeUploadDir}/${file.name}`);
}
}
return NextResponse.json({ filename: folderArray });
} catch (e) {
console.error("Error while trying to upload a file\n", e);
return NextResponse.json({ error: "Что-то пошло не так" }, { status: 500 });
}
}