Express Exceptional Download - Check File Extension, Move and Remove

I am working on a file upload form using Express 4 and Formidable and am having some problems.

I am trying to achieve:

-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 check for "if file is selected" and format and how to check? Can I check for 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 executing form.parse

    ?

  • Is this the correct way to move the file and into the correct event? But how can I abort if "write to db" or "move file" fails? Can this be done with async?

+3


source to share





All Articles