Proper way to use connect-multiparty with express.js?

Eric picture Eric · Oct 2, 2015 · Viewed 12.1k times · Source

I am trying to upload files to my server and extract them from the post request using the connect-multiparty middleware. However, when I receive the request on the server, the req.files and req.body objects are empty (not null, but node-inspector shows that they are Objects with nothing in them.

Here is the code that I'm working with:

server.js:

var express = require( "express" );
var app = express();
var server = require( "http" ).Server( app );
var fs = require( "fs" );
var multipart = require('connect-multiparty');

app.use( express.static( "public" ) );
app.use( multipart() );

app.post( "/httpUpload", function( req, res ) {
    console.log( "Received post request" );
}

index.html:

<form action="/httpUpload" method="post" enctype="multipart/form-data">
  <input type="file" id="uploadFileInput">
  <div class="row">
    <div class="col-md-6">
      <input type="submit">
    </div>
  </div>
</form>

I've gotten similar results trying to use multer, connect-busboy, and body-parser. I would have loved if this solution worked for me, but it didn't: http://howtonode.org/really-simple-file-uploads

So ... the only common theme in all of my failed attempts is me. ;o) Any ideas what I'm doing wrong?

Answer

Med Tumy picture Med Tumy · Jan 17, 2016

here is my way of extracting the uploaded files :

var express = require('express');
var multiparty = require('connect-multiparty'),
    multipartyMiddleware = multiparty({ uploadDir: './imagesPath' });

var router = express.Router();

router.post('/', multipartyMiddleware, function(req, res) {
  console.log(req.body, req.files);
  var file = req.files.file;
  console.log(file.name);
  console.log(file.type);
  res.status(200).send('OK');
});

module.exports = router;

this will save you uploded files to imagesPath folder