Reputation: 83
I've been trying to upload two different files (image and pdf) by using Multer and I can't figure out how to manipulate the files inside of fileFilter. I want to check for the file type and size - which works, and then take the pdf file and store it on the disk while the image file continues to another function handling image processing. I'm new to this and tried many guides but non of them shows this scenario.
Thank you in advance for your help.
Code for Multer and router. It's still a bit rough so please bear with me.
// multer configuration
const upload = multer({
storage: multer.memoryStorage(),
fileFilter (req, files, callback) {
const ext = path.extname(files.originalname);
if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg' && ext !== '.pdf') {
return callback(new Error('Only images and pdf files allowed'));
}
callback(null, true);
},
limits: {
fileSize: 5242880,
}
}).fields([{ name: 'main image', maxCount: 1 }, { name: 'info packs', maxCount: 1 }]);
// router
router.post('/', upload, controller.addNewImage);enter code here
Upvotes: 1
Views: 2033
Reputation: 896
I think this is ok:
const upload = multer({
storage: multer.memoryStorage(),
fileFilter (req, files, callback) {
const ext = path.extname(files.originalname);
const allowed = ['.png', '.jpg', '.jpeg', '.pdf'];
if (allowed.includes(ext)) {
callback(null, true);
} else {
callback(null, false); // handle error in middleware, not here
}
},
limits: {
fileSize: 5242880,
}
}).fields([{ name: 'main image', maxCount: 1 }, { name: 'info packs', maxCount: 1 }]);
Upvotes: 1