1

What is the standard practice of handling file uploads and validating text fields/insert to db in Nodejs, sequelize, and connect-busboy?

For example, if we have a user profile form where an enduser has to input a name, email, and upload few files.

When the user submits the form, would the steps on the server be, (1) validate text fields (2) save to User table in db (3) save files to disk (4) update user row with filepaths

In semi-pseudo-code, I am imagining something like:

router.post('/formSubmit', function(req, res) {
    var name = ....;
    var email = ...;
    var files = [];

    // Sequelize will validate for us when creating a new row in User table
    User.create({ name: name, email: email}).success(function(user_row) {

        // save each files to disk
        ...

        // update user_row with the filepaths on disk.
        ...
    });
});

But, I'm not sure how to adapt this logic flow into connect-busboy:

router.post('/formSubmit', busboy, function(req, res) {
    if (req.busboy) {
        busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
          var saveTo = path.join(os.tmpDir(), path.basename(fieldname));
          file.pipe(fs.createWriteStream(saveTo));
        });
        busboy.on('field', function(key, value, keyTruncated, valueTruncated) {
            // ...
        });
        busboy.on('finish', function() {
          res.writeHead(200, { 'Connection': 'close' });
          res.end("That's all folks!");
        });
        return req.pipe(busboy);
    }
    res.writeHead(404);
    res.end();
});

Do I have the right idea? If so, how can I adapt the validations, user creation/update into connect-busboy?

If I'm way off, what's the standard practice of doing db validations, create/update of user fields, and also including the user uploads?

rublex
  • 1,893
  • 5
  • 27
  • 45
  • If you need to validate the other fields *before* handling the file(s), make sure that those other fields come *before* the file field(s) in your form submission. Those non-file field(s) will be emitted as `field` events. – mscdex Apr 14 '15 at 05:47
  • @mscdex How would I know when to create/update the User row in the database if the fields are emitted one by one? ie, it seems like I can't do this `User.create({ name: name, email: email})` if I don't know all the fields beforehand? – rublex Apr 14 '15 at 06:31
  • 1
    Just wait until all of the values are collected? You could put them in an object or use separate variables. If you end up seeing the file field or the `finish` event first, then user didn't submit all the required values. In that case just respond with an appropriate HTTP status code. – mscdex Apr 14 '15 at 14:18
  • in case somebody come across this issue, here is a gist https://gist.github.com/rhamedy/8f29ec90a00fcf8fec8f2c82bd34d10e that basically upload multiple files and does a few checks (i.e. size, mimetype, etc.) – Raf Feb 26 '17 at 21:05

0 Answers0