ImageUploader

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

fileUploader.ts (741B)


      1 "use server";
      2 import { promises as fs } from "node:fs";
      3 import { resolve } from "node:path";
      4 import { revalidatePath } from "next/cache";
      5 
      6 export async function fileUploader(formData: FormData) {
      7   const file = formData.get("file") as File;
      8   let filePath = 'uploads/c5fdf674-4dde-4a2c-8549-4c6d811f2fbc.pdf';
      9   let fileName = 'c5fdf674-4dde-4a2c-8549-4c6d811f2fbc.pdf';
     10   if (file && file.size > 0) {
     11     const data = await file.arrayBuffer();
     12     const buffer = Buffer.from(data);
     13     fileName = `${crypto.randomUUID()}.${file.name.split(".").pop()}`
     14     filePath = resolve(
     15       process.cwd(),
     16       "./public/uploads",
     17       fileName,
     18     );
     19     await fs.writeFile(filePath, buffer);
     20   }
     21   revalidatePath("/file");
     22 
     23   return fileName;
     24 }