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

£可爱£侵袭症+ 提交于 2019-12-02 09:50:52

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

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;
    }
  })
});

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!