I have never written a question before, because I have always found an answer here to my issues prior to asking. However I am struggling with a fileFilter function on a file upload POST route on express. I have used the multer upload function in the route, and also as middleware, with an error handling middleware following, and cannot get it to behave as I expect.
I am expecting the 'LIMIT_UNEXPECTED_FILE' error to trigger a flash message, and then a redirect to the same page where the file upload is being chosen. This happens sometimes, but is not consistent. If multiple upload attempts fail in a row during my testing, the third or fourth time the request will hang.
I know the fileFilter function is running, and outputs the correct error, because I have multiple console.logs in my upload function inside the post route, and it outputs the correct error. The problem is the req.flash and then res.redirect are not getting triggered.
When I was using the upload function as middleware in the post route, and then another middleware function after the post route to handle the error, I was also having issues with the res.redirect not triggering. Not sure what I'm missing here?
index.js
// set upload destination and filename for uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './public/uploads/');
},
filename: (req, file, cb) => {
const {
originalname
} = file;
cb(null, `${uuid()}-${originalname}`);
},
});
// filter by file types uploaded
const fileFilter = (req, file, cb) => {
console.log(file.mimetype);
if (file.mimetype.split('/')[0] === 'image') {
cb(null, true);
} else {
cb(new multer.MulterError('LIMIT_UNEXPECTED_FILE'), false);
}
};
const upload = multer({
storage,
fileFilter,
limits: {
fileSize: 5 * 1024 * 1024
}
}).single('document');
// Upload route - logged in
router.post('/app/admin/upload', function(req, res) {
if (req.isAuthenticated()) {
console.log('testing1');
upload(req, res, (err) => {
if (err) {
console.log(err.code);
if (err.code === 'LIMIT_FILE_SIZE') {
req.flash('docError', 'File upload failed due to file size');
res.redirect('back');
} else if (err.code === 'LIMIT_FILE_COUNT') {
req.flash('docError', 'File upload failed due to file count');
res.redirect('back');
} else if (err.code === 'LIMIT_UNEXPECTED_FILE') {
console.log('testing2');
req.flash('docError', 'File upload failed due to file type');
res.redirect('back');
} else {
console.log(err.code);
req.flash('docError', 'File upload failed due to unknown error');
res.redirect('back');
}
} else {
if (!req.file) {
req.flash('docError', 'No file chosen to upload');
res.redirect('back');
} else {
req.flash('docSuccess', 'File uploaded successfully');
res.redirect('back');
}
}
});
} else {
res.redirect('/');
}
});
Server console output when triggering upload post route
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
listening on port 3000
testing12345
application/x-msdownload
LIMIT_UNEXPECTED_FILE
testing 23456