-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmulterConfig.js
47 lines (42 loc) · 1.33 KB
/
multerConfig.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import multer from "multer";
import path from "path";
import { getFileExtension } from "./helper.js";
import { nanoid } from "nanoid";
export const whiteList = {
csv: "text/csv|application/vnd.ms-excel",
pdf: "application/pdf",
txt: "text/plain",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
};
const isMimeAllowed = (type, mimeType) => {
if (!whiteList[type]) return false;
return whiteList[type].split("|").includes(mimeType);
};
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const filePath = path.join(path.resolve(), "uploads");
cb(null, filePath);
},
filename: function (req, file, cb) {
const fileExt = path.extname(file.originalname);
cb(null, `${file.fieldname}-${nanoid(10)}${fileExt}`);
},
});
const fileFilter = (req, file, cb) => {
if (
isMimeAllowed(getFileExtension(file.originalname), file.mimetype) && // check file type
Object.keys(whiteList).includes(getFileExtension(file.originalname)) // check file extension
) {
cb(null, true);
} else {
cb(null, false);
let msg = `Only .${Object.keys(whiteList)
.join(", .")
.toUpperCase()} formats are allowed!`;
return cb(new Error(msg));
}
};
export const upload = multer({
storage,
fileFilter,
});