2
votes

I am trying to upload a file to my server, but req.file and req.files is always undefined on my POST REST endpoint.

The content I'm trying to upload is a ".dat" file, and I am expecting a json response.

Here's my code:

Server side:

var express = require('express');
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/creoUpload', upload.single('uploadFileField'), function(req, res, next) {
  console.log("req.file = ",JSON.stringify(req.file)); //is undefined
  console.log("req.files = ",JSON.stringify(req.files)); //also undefined
});

Client Side:

<form id="creoUploadForm" action="/creoUpload" enctype="multipart/form-data" method="post">
    <input type='file' name='uploadFileField'><br><br>
    <input type='submit' value='Upload'/>
</form>

JS:

$( "#creoUploadForm" ).submit(function( event ) {
    event.preventDefault();
    var formData = new FormData($(this)[0]);
    $.ajax({
          url: '/creoUpload',
          type: 'POST',
          data: formData,
          async: true,
          cache: false,
          contentType: false,
          processData: false,
          success: function (returndata) {
              console.log("RETURN DATA IS: ",returndata);
          },
          error: function (err) {
              console.log("ERROR: ",err);
          }
    });
});

I keep playing around with the fields but it's not working.. anyone see what I'm doing wrong here?

I'm following the example from https://www.npmjs.com/package/multer

Versions:

  • Express Version: 4.12.0
  • Node Version: 6.5.0
  • JQuery: 1.12.1

Thank you!

4
In your HTML, can you try removing the action from the form tag, and adding formaction="/creoupload" to the submit button?ecg8
try to send post request with fetch ApiiLyas

4 Answers

3
votes

I have the same issue, if you check the documentation on the Error Handling section there is another kind of implementation, that's the one that works for me. The code will be something like this:

var express = require('express');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var app = express();

app.post('/creoUpload', function(req, res, next) {
  upload(req, res, function (err) {
    if (err) {
      // An error occurred when uploading
      console.log('Err: ', err);
      return;
    } else {
       console.log('req.file: ', JSON.stringify(req.file));  
       console.log('req.files: ', JSON.stringify(req.files));
       return;
    }
  })
});
3
votes

You are using multer as a middleware, So before entering into your function and printing it has uploaded images to storage and removes record from req.files.

There are two ways you can access req.files.

  1. Use multer as a function stated by finw3.

  2. Another solution is:

//CODE STARTS

var storage = multer.diskStorage({

  destination: function (req, file, cb) {

    cb(null, '/filepath')
  },


  filename: function (req, file, cb) {

    let filename = 'filenametogive';
     req.body.file = filename

    cb(null, filename)
  }
})

var upload = multer({ storage: storage })

//CODE ENDS

Now you can access files in req.body.file

2
votes

Don't set contentType to false, as POST method requires contentType = 'w-xxx-form-urlencoded', which is the JQ default.

1
votes

If the req.file and req.files are undefined, then the problem is that multer did not receive the uploaded file and this issue seems related to jQuery.

Uploading a FormData with jQuery 'v1.12.1' is not supported and it won't send anything at all. I will recommend to try with fetch Api or change the version of your jQuery to 3.3.1.

I already tested the code and I have successfully upload a file to my server when I change my jQuery version from v1.12.1 to v3.3.1.