feat: media library with image picker for article forms, browse/upload from folder
This commit is contained in:
1 parent
d35c495539
commit
12576cc113
9 files changed
+392
-19
No files matched your search
@@ -0,0 +1,66 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { writeFile, mkdir } from "fs/promises";
|
||||
import path from "path";
|
||||
import { requireStaff } from "@/lib/admin/guard";
|
||||
|
||||
const MEDIA_DIR = "public/assets/images/media";
|
||||
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
|
||||
const ALLOWED = ["image/png", "image/jpeg", "image/gif", "image/webp"];
|
||||
|
||||
export async function uploadMedia(formData: FormData): Promise<void> {
|
||||
await requireStaff();
|
||||
const file = formData.get("file") as File | null;
|
||||
if (!file || file.size === 0) return;
|
||||
if (file.size > MAX_SIZE) throw new Error("File too large (max 5MB)");
|
||||
if (!ALLOWED.includes(file.type)) throw new Error("Invalid file type");
|
||||
|
||||
const dir = path.join(process.cwd(), MEDIA_DIR);
|
||||
await mkdir(dir, { recursive: true });
|
||||
|
||||
const ext = file.name.split(".").pop() ?? "png";
|
||||
const name = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
|
||||
const bytes = await file.arrayBuffer();
|
||||
await writeFile(path.join(dir, name), Buffer.from(bytes));
|
||||
|
||||
revalidatePath("/api/media");
|
||||
revalidatePath("/admin/media");
|
||||
}
|
||||
|
||||
export async function deleteMedia(name: string): Promise<void> {
|
||||
await requireStaff();
|
||||
const { unlink } = await import("fs/promises");
|
||||
const dir = path.join(process.cwd(), MEDIA_DIR);
|
||||
const filePath = path.join(dir, name);
|
||||
// Prevent path traversal
|
||||
if (name.includes("..") || name.includes("/")) return;
|
||||
try {
|
||||
await unlink(filePath);
|
||||
} catch {
|
||||
// File may not exist
|
||||
}
|
||||
revalidatePath("/api/media");
|
||||
revalidatePath("/admin/media");
|
||||
}
|
||||
|
||||
export async function uploadMediaAndReturn(formData: FormData): Promise<string> {
|
||||
await requireStaff();
|
||||
const file = formData.get("file") as File | null;
|
||||
if (!file || file.size === 0) return "";
|
||||
if (file.size > MAX_SIZE) return "";
|
||||
if (!ALLOWED.includes(file.type)) return "";
|
||||
|
||||
const dir = path.join(process.cwd(), MEDIA_DIR);
|
||||
await mkdir(dir, { recursive: true });
|
||||
|
||||
const ext = file.name.split(".").pop() ?? "png";
|
||||
const name = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
|
||||
const bytes = await file.arrayBuffer();
|
||||
await writeFile(path.join(dir, name), Buffer.from(bytes));
|
||||
|
||||
revalidatePath("/api/media");
|
||||
revalidatePath("/admin/media");
|
||||
return `/assets/images/media/${name}`;
|
||||
}
|
||||
Reference in new issue
Block a user