|
1
|
import multer from "multer"; |
|
2
|
import path from "path"; |
|
3
|
import fs from "fs"; |
|
4
|
|
|
5
|
// Ensure uploads directory exists |
|
6
|
const uploadDir = "uploads/profiles"; |
|
7
|
if (!fs.existsSync(uploadDir)) { |
|
8
|
fs.mkdirSync(uploadDir, { recursive: true }); |
|
9
|
} |
|
10
|
|
|
11
|
const storage = multer.diskStorage({ |
|
12
|
destination: function (_req, _file, cb) { |
|
13
|
cb(null, uploadDir); |
|
14
|
}, |
|
15
|
filename: function (_req, file, cb) { |
|
16
|
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9); |
|
17
|
cb(null, uniqueSuffix + path.extname(file.originalname)); |
|
18
|
}, |
|
19
|
}); |
|
20
|
|
|
21
|
export const upload = multer({ |
|
22
|
storage: storage, |
|
23
|
limits: { |
|
24
|
fileSize: 5 * 1024 * 1024, // 5MB limit |
|
25
|
}, |
|
26
|
fileFilter: (_req, file, cb) => { |
|
27
|
if (file.mimetype.startsWith("image/")) { |
|
28
|
cb(null, true); |
|
29
|
} else { |
|
30
|
cb(new Error("Only image files are allowed!")); |
|
31
|
} |
|
32
|
}, |
|
33
|
}); |