I'm tryng to upload a file and the upload goes ok! The problem is when I try to upload some file that is not accepted according to me fileFitler handling. I would like to receive some error in console or redirect the user to the back page, but I'm just receiving a error on brower : cannot read read property filename of undefined.
But, if I upload some extension that is accepted, goes ok!
Here is my code:
const mongoose = require('mongoose');
const multer = require('multer');
const uuidV4 = require('uuid/v4');
const Video = require('../models/videoModel');
function fileFilter(req, file, cb){
const extension = file.mimetype.split('/')[0];
if(extension !== 'video'){
return cb(null, false), new Error('Something went wrong');
}
cb(null, true);
};
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
const newName = uuidV4();
const extension = file.mimetype.split('/')[1];
cb(null, newName +`.${extension}`);
}
});
var upload = multer({ storage: storage, fileFilter: fileFilter});
exports.uploadVideo = upload.single('file'); // the single param should be the name of the file input form
exports.CreateVideo = (req, res) => {
const newVideo = {title: req.body.title, path: req.file.filename};
Video.create(newVideo, function(err, result){
if(err){
console.log('Não foi possível realizar o upload do vídeo.' + err);
}
else{
console.log('Vídeo upado com sucesso!');
res.redirect('/');
console.log(result);
}
})
};
exports.Home = (req, res) =>{
res.render('index');
};
exports.ShowVideos = (req, res) =>{
Video.find({}, function(err, result){
if(err){
res.redirect('/');
}
else{
res.render('video', {videoData:result});
}
})
};
The get an error on the console, you could change your fileFilter
and pass an error to the cb
function. See:
function fileFilter(req, file, cb){
const extension = file.mimetype.split('/')[0];
if(extension !== 'video'){
return cb(new Error('Something went wrong'), false);
}
cb(null, true);
};
Hope it helps!!