28 lines
920 B
JavaScript
28 lines
920 B
JavaScript
import multer from "multer";
|
|
import path from "path";
|
|
import crypto from "crypto";
|
|
import { fileURLToPath } from "url";
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
export const UPLOAD_DIR = path.join(__dirname, "uploads");
|
|
|
|
const ALLOWED = new Set(["image/gif", "image/png", "image/webp"]);
|
|
|
|
const storage = multer.diskStorage({
|
|
destination: (_req, _file, cb) => cb(null, UPLOAD_DIR),
|
|
filename: (_req, file, cb) => {
|
|
const ext = path.extname(file.originalname).toLowerCase().replace(/[^.a-z0-9]/g, "");
|
|
const safeExt = [".gif", ".png", ".webp"].includes(ext) ? ext : ".gif";
|
|
cb(null, crypto.randomUUID() + safeExt);
|
|
},
|
|
});
|
|
|
|
export const upload = multer({
|
|
storage,
|
|
limits: { fileSize: 8 * 1024 * 1024 }, // 8 MB
|
|
fileFilter: (_req, file, cb) => {
|
|
if (ALLOWED.has(file.mimetype)) cb(null, true);
|
|
else cb(new Error("Only GIF, PNG, or WebP images are allowed"));
|
|
},
|
|
});
|