Created
August 22, 2024 20:27
-
-
Save jsstoni/d585d38d4f95536fd193bb3d3abf0fed to your computer and use it in GitHub Desktop.
upload image
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 { 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