Last active
July 22, 2024 10:02
-
-
Save bonface221/d65f1ca644c1154d7deb2561bf455667 to your computer and use it in GitHub Desktop.
saving files in nextjs on the public folder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use server"; | |
import path from "path"; | |
import fs from "fs"; | |
import { uuid } from "uuidv4"; | |
const UPLOAD_DIR = path.resolve(process.env.ROOT_PATH ?? "", "public/uploads"); | |
export const SaveFileAction = async (data: FormData) => { | |
const body = Object.fromEntries(data); | |
const file = (body.file as Blob) || null; | |
const fileExt = (body.file as File).name.split(".").pop(); | |
const uuidString = uuid(); | |
const newFileName = `${uuidString}.${fileExt}`; | |
if (file) { | |
const buffer = Buffer.from(await file.arrayBuffer()); | |
if (!fs.existsSync(UPLOAD_DIR)) { | |
fs.mkdirSync(UPLOAD_DIR); | |
} | |
fs.writeFileSync(path.resolve(UPLOAD_DIR, newFileName), buffer); | |
} else { | |
return { | |
status: false, | |
file: null, | |
}; | |
} | |
return { | |
status: true, | |
file: newFileName, | |
}; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment