Skip to content

Instantly share code, notes, and snippets.

@jsstoni
Created August 22, 2024 20:27
Show Gist options
  • Save jsstoni/d585d38d4f95536fd193bb3d3abf0fed to your computer and use it in GitHub Desktop.
Save jsstoni/d585d38d4f95536fd193bb3d3abf0fed to your computer and use it in GitHub Desktop.
upload image
"use server";
import { writeFile } from "fs/promises";
import path from "path";
export const uploadImage = async (data: FormData): Promise<string> => {
const image = data.get("image") as File | null;
if (!image) {
throw new Error("Image no found");
}
const allowedMimeTypes = ["image/jpeg", "image/png", "image/webp"];
if (!allowedMimeTypes.includes(image.type)) {
throw new Error("Invalid image type");
}
const allowedExtensions = [".jpg", ".jpeg", ".png", ".webp"];
const extension = path.extname(image.name).toLowerCase();
if (!allowedExtensions.includes(extension)) {
throw new Error("Invalid file extension");
}
const safeFileName = generateToken(16) + extension;
const bytes = await image.arrayBuffer();
const buffer = Buffer.from(bytes);
const uploadDir = path.join(process.cwd(), "public", "upload");
const filePath = path.join(uploadDir, safeFileName);
await writeFile(filePath, buffer);
return safeFileName;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment