Initial commit
This commit is contained in:
40
server/middleware/upload.js
Normal file
40
server/middleware/upload.js
Normal file
@@ -0,0 +1,40 @@
|
||||
const multer = require('multer');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const uploadDir = path.join(__dirname, '../uploads');
|
||||
if (!fs.existsSync(uploadDir)) {
|
||||
fs.mkdirSync(uploadDir, { recursive: true });
|
||||
}
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination(req, file, cb) {
|
||||
cb(null, uploadDir);
|
||||
},
|
||||
filename(req, file, cb) {
|
||||
cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`);
|
||||
}
|
||||
});
|
||||
|
||||
function checkFileType(file, cb) {
|
||||
const filetypes = /jpg|jpeg|png|webp|svg|mp4|webm/;
|
||||
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
|
||||
const mimetype = filetypes.test(file.mimetype);
|
||||
|
||||
if (extname && mimetype) {
|
||||
return cb(null, true);
|
||||
} else {
|
||||
cb(new Error('Images and video media only!'));
|
||||
}
|
||||
}
|
||||
|
||||
const upload = multer({
|
||||
storage,
|
||||
limits: { fileSize: 10 * 1024 * 1024 }, // 10MB limit
|
||||
fileFilter: function (req, file, cb) {
|
||||
checkFileType(file, cb);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = upload;
|
||||
|
||||
Reference in New Issue
Block a user