Search code examples
node.jsexpressform-databody-parser

Get form-data in Nodejs


I have an app on nodejs and I already get the requests in json format (No issue here).

The problem comes when I want to upload a video through form-data. Here is a little bit of my code:

Server.js

var express = require('express');
var bodyparser = require('body-parser');

var app = express();

app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json());
require('./routes/routes')(app);

Routes.js

module.exports = function(app){
app.post('/save', ensureAuthenticated, activity.publish); //JSON REQUEST
app.post('/video', ensureAuthenticated, activity.video); //FORM-DATA REQUEST
}

I try to use express-formidable (in Server.js) but it breaks my '/save' route. Anyone has an idea?


Solution

  • I advice you to use multer

    https://github.com/expressjs/multer

    Example:

    var express = require('express')
    var multer  = require('multer')
    var upload = multer({ dest: 'uploads/' })
    
    var app = express()
    
    app.post('/profile', upload.single('avatar'), function (req, res, next) {
      // req.file is the `avatar` file
      // req.body will hold the text fields, if there were any
    })
    
    app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
      // req.files is array of `photos` files
      // req.body will contain the text fields, if there were any
    })
    
    var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
    app.post('/cool-profile', cpUpload, function (req, res, next) {
      // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
      //
      // e.g.
      //  req.files['avatar'][0] -> File
      //  req.files['gallery'] -> Array
      //
      // req.body will contain the text fields, if there were any
    })