javascriptjquerynode.jsexpressmulter

node js multer file upload not working. req.file and req.files always undefined


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:

Thank you!


Solution

  • 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