Getting formidable form object in Express 3.0 on upload

The recent versions of Express frameworks, not only recent use for form handling the middleware bodyParser which makes uploading easy. Only problem is that the form object is not added to request object so you can not listen for some of the useful events like progress. To get the access to formidable form object you have to remove the multipart handling from middleware.

What does this mean ?

    app.use(express.bodyParser());

Is equal to this and now we have possibility to remove the multipart handling from middleware:

    app.use(express.json());
    app.use(express.urlencoded());
    app.use(express.multipart()); // Remove this line

Now comes the handling part on request:

exports.upload = function(req, res) {
    var form = new formidable.IncomingForm;
    form.keepExtensions = true;
    form.uploadDir = 'tmp/';

    form.parse(req, function(err, fields, files){
      if (err) return res.end('You found error');
      // do something with files.image etc
      console.log(files.image);
    });

    form.on('progress', function(bytesReceived, bytesExpected) {
        console.log(bytesReceived + ' ' + bytesExpected);
    });

    form.on('error', function(err) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.end('error:\n\n'+util.inspect(err));
    });
    res.end('Done');
    return;
};

Screenshot from 2012-12-02 10:53:11

Well this kind of form object creation is only needed if you want to access the events. If not use the default bodyParser’s multipart middleware which holds the code cleaner and you still can access the files properties like name, size etc.

4 thoughts on “Getting formidable form object in Express 3.0 on upload

  1. Even If I set form.uploadDir = ‘tmp/’; I will be uploaded to :
    path /var/folders/_v/tq1vcbk91md5tq1dg6krcqs40000gn/T/9e508a5bca43d8c13bc753a3bc15fa67

    any idea whats wrong ?

    • Hello,

      Well I haven’t used formidable for long time, but first you could try to use different package versions. Also if the uploadDir option is not overridden with your own value, try to check what require(‘os’).tmpDir() results to you ?

  2. Hi, I think your website might be having browser compatibility issues.

    When I look at your blog in Ie, it looks fine but when opening in Internet Explorer,
    it has some overlapping. I just wanted to give you
    a quick heads up! Other then that, excellent blog!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s