Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multipart/form-data upload - Nodejs - expressjs

Since express.multipart is removed from the Express 4.x library, what will be the best way to handle file upload in expressjs?

like image 844
nilveryboring Avatar asked Apr 12 '14 07:04

nilveryboring


1 Answers

Just answered a similar question about multipart. I would recommend multiparty:

Have you given node-multiparty a try? Here's example usage from the README:

var multiparty = require('multiparty')
  , http = require('http')
  , util = require('util')

http.createServer(function(req, res) {
  if (req.url === '/upload' && req.method === 'POST') {
    // parse a file upload
    var form = new multiparty.Form();

    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(util.inspect({fields: fields, files: files}));
    });

    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title"><br>'+
    '<input type="file" name="upload" multiple="multiple"><br>'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(8080);

The author (Andrew Kelley) recommends avoiding bodyParser, so you're right to avoid it, but multiparty seems to solve a similar issue for me.

like image 69
kentcdodds Avatar answered Sep 22 '22 09:09

kentcdodds