I am working on a file upload form with Express 4 and Formidable and have some problems.
What I'm trying to achieve is:
-Check if file is selected and extension/format before file is uploaded to the server and abort if not .txt
-Write file "info" to db, copy file from tmp folder to dest. folder and delete tmp file.
My code:
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname, '/uploads/tmp');
form.keepExtensions = true;
form.on('error', function(err) {
console.log(err.message);
req.flash('error', err.message);
res.redirect('/upload');
});
form.on('file', function(name, file){
var modname = file.path.split('/')[file.path.split('/').length-1]
var finals = path.join(__dirname, 'uploads/finals/' + modname);
fs.rename(file.path, finals, function(err){
if(err) throw err;
});
new Input({
user: req.user,
name: file.name,
size: file.size,
path: finals,
type: file.type
}).save(function(err, upload, count){
if (err){
console.log(err);
}
});
});
form.on('end', function (){
req.flash('info', 'Input file uploaded');
res.redirect('/upload');
});
form.parse(req);
});
I'm not sure where to put the check for "if file is selected" and format and how to check? Can I check if the size === 0 and then emit an error event? If how to do this or is there any other way i can check if a file is selected before the
form.parse
is executed?Is this the correct way to move the file and in the right event? But how can I abort if either the "write to db" or "move file" fails? Can this be done with async?