File size: 1,584 Bytes
057576a | 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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | const multer = require('multer');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
// Configure storage
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
const uniqueName = `${uuidv4()}${path.extname(file.originalname)}`;
cb(null, uniqueName);
}
});
// File filter
const fileFilter = (req, file, cb) => {
const allowedTypes = {
'image/jpeg': true,
'image/jpg': true,
'image/png': true,
'image/gif': true,
'image/webp': true,
'audio/mpeg': true,
'audio/wav': true,
'audio/ogg': true,
'audio/mp4': true,
'application/pdf': true,
'text/plain': true,
'text/markdown': true
};
if (allowedTypes[file.mimetype]) {
cb(null, true);
} else {
cb(new Error(`File type ${file.mimetype} is not supported`), false);
}
};
const upload = multer({
storage,
fileFilter,
limits: {
fileSize: 50 * 1024 * 1024 // 50MB max file size
}
});
// Error handling middleware for multer
const handleUploadError = (error, req, res, next) => {
if (error instanceof multer.MulterError) {
if (error.code === 'LIMIT_FILE_SIZE') {
return res.status(400).json({ error: 'File too large. Maximum size is 50MB.' });
}
return res.status(400).json({ error: `Upload error: ${error.message}` });
}
if (error) {
return res.status(400).json({ error: error.message });
}
next();
};
module.exports = { upload, handleUploadError }; |