3

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?

Eric
  • 1,414
  • 3
  • 16
  • 35

2 Answers2

2

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

Med Tumy
  • 1,705
  • 2
  • 11
  • 20
  • 1
    Do we need to remove the file from the uploaded directory after processing it or saving it? – Rohit Khatri Sep 22 '18 at 11:10
  • Using this, the file is uploaded before reaching the callback function. I want to upload the file after a few checks like type/size etc. How can we achieve this? – Rahul Munjal May 15 '21 at 09:30
1

Well ... this isn't quite an answer to my question, but when I changed my code to remove the form and send the post request via jQuery's ajax method, the req.files object had my data in it. (shrug) Here was the code in my js that made it work:

$.ajax( {
    url: "/httpUpload",
    type: "POST",
    processData: false, // important
    contentType: false, // important
    dataType : "json",
    data: formData
} );

This is the post that put me on the right path: File Upload without Form

Community
  • 1
  • 1
Eric
  • 1,414
  • 3
  • 16
  • 35
  • 2
    This is because as per the README, you need to use the multipary Form() object to use forms: https://github.com/pillarjs/multiparty#usage – sijpkes May 27 '17 at 04:04