Skip to content

Instantly share code, notes, and snippets.

@bonface221
Last active July 22, 2024 10:02
Show Gist options
  • Save bonface221/d65f1ca644c1154d7deb2561bf455667 to your computer and use it in GitHub Desktop.
Save bonface221/d65f1ca644c1154d7deb2561bf455667 to your computer and use it in GitHub Desktop.
saving files in nextjs on the public folder
"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