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

5

2

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!

Macaronic answered 24/2, 2018 at 1:4 Comment(2)
In your HTML, can you try removing the action from the form tag, and adding formaction="/creoupload" to the submit button?Longley
try to send post request with fetch ApiCarycaryatid
T
5

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

Teletype answered 24/2, 2018 at 10:46 Comment(0)
L
3

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;
    }
  })
});
Lundt answered 24/2, 2018 at 2:59 Comment(0)
C
2

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

Cornellcornelle answered 24/2, 2018 at 17:51 Comment(0)
C
1

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.

Carycaryatid answered 24/2, 2018 at 3:27 Comment(0)
S
0

Tried with mulipartfile method in the flutter and tierd. use below

use base64 encoding for the files. lang:dart

Read file as bytes and encode to base64.

List<int> fileBytes = await File(filePath).readAsBytes();
String base64Video = base64Encode(fileBytes);

// Create request payload
Map<String, dynamic> payload = {
  'email': '[email protected]',
  'userId': '0001',
  'file': base64Video,
  'fileName': fileName,
  'mimeType': mimeType,
};

Then at the server end Decode base64 string to binary data. lang:express.js

const binaryData = Buffer.from(file, 'base64');
const uploadPath = path.join(__dirname, "../videos", fileName);
fs.writeFileSync(uploadPath, binaryData);
Sentimentalism answered 28/7 at 7:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.