"use server"; import { randomBytes } from "node:crypto"; import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { getCurrentUser, can } from "./auth"; const EXT: Record = { "image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp", "image/gif": ".gif", "image/avif": ".avif" }; // Bilder werden unverändert in Originalgröße gespeichert, nicht verkleinert oder neu komprimiert. const MAX_MB = 25; export async function uploadImages(fd: FormData): Promise<{ urls: string[]; error?: string }> { const user = await getCurrentUser(); if (!can(user, "products.edit") && !can(user, "categories.edit") && !can(user, "appearance.edit") && !can(user, "consulting.own")) return { urls: [], error: "Dafür fehlt dir das Recht." }; const dir = path.resolve(process.env.UPLOAD_DIR ?? "./uploads"); await mkdir(dir, { recursive: true }); const urls: string[] = []; for (const file of fd.getAll("files")) { if (!(file instanceof File) || file.size === 0) continue; const ext = EXT[file.type]; if (!ext) return { urls, error: `${file.name}: Bitte JPG, PNG, WebP, AVIF oder GIF hochladen. iPhone-Fotos (HEIC) wandelt das iPhone beim Hochladen automatisch um.` }; if (file.size > MAX_MB * 1024 * 1024) return { urls, error: `${file.name} ist größer als ${MAX_MB} MB.` }; const name = `${Date.now().toString(36)}-${randomBytes(6).toString("hex")}${ext}`; await writeFile(path.join(dir, name), Buffer.from(await file.arrayBuffer())); urls.push(`/uploads/${name}`); } return { urls }; }