Search code examples
node.jsexpressmeteoriron-router

Parsing form-data using Meteor


I'm having an issue parsing multipart/form-data using Meteor

Here is my route:

this.route('mail', {
  where: 'server',
  path: '/mail',
  action: function () {
    console.log(this.request.body);
    this.response.end('get request\n');
  }
});

urlEncoded and JSON data work fine


Solution

  • This is a bug in iron-router parsing multipart/form-data: https://github.com/EventedMind/iron-router/issues/909

    Can solve in the meantime by using the Busyboy module:

    var Busboy = Meteor.npmRequire("busboy")
    var fs     = Npm.require("fs");
    var os     = Npm.require("os");
    var path   = Npm.require("path");
    
    Router.onBeforeAction(function (req, res, next) {
      var filenames = []; // Store filenames and then pass them to request.
    
      if (req.method === "POST") {
        var busboy = new Busboy({ headers: req.headers });
    
        busboy.on("file", function (fieldname, file, filename, encoding, mimetype) {
          var saveTo = path.join(os.tmpDir(), filename);
          file.pipe(fs.createWriteStream(saveTo));
          filenames.push(saveTo);
        });
    
        busboy.on("field", function(fieldname, value) {
          req.body[fieldname] = value;
        });
    
        busboy.on("finish", function () {
          // Pass filenames to request
          req.filenames = filenames;
          next();
        });
    
        // Pass request to busboy
        req.pipe(busboy);
      } else {
        next();
      }
    });