Solution Cannot read property ‘path’ of undefined – Upload files in NodeJS – Victor Robles


When we are trying upload files in NodeJSDepending on the library we use, we can have more or less problems when uploading any file, image or whatever.

One of the most common errors that you can have with libraries like multiparty, connect-multiparty, express-fileupload, formidable, even multer, is that they appear path property errors like this:

TypeError: Cannot read property 'path' of undefined

The problem is that with certain versions of express, the upload of files (multipart / form-data) is not being processed correctly and some libraries have stopped working in some isolated cases.

To fix this, we are going to use a file upload library in NodeJS called Multer.

The first thing to do is install multer:

npm install --save multer

Then in the file in which we are configuring our routes we will do the following steps.

PASO 1. Load the file upload module:

const multer = require('multer');

PASO 2. Configure where the files will be uploaded on the server and what the name of those files will be:

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './uploads/users/')
    },
    filename: function (req, file, cb) {
        cb(null, "user" + Date.now() + file.originalname);
    }
  });

PASO 3. Create the multer object and pass the configuration to it:

const upload = multer({ storage: storage }); 

PASO 5. In the file upload endpoint use the upload.single (“name of the field to upload”) middleware to finally upload the file:

router.post('/upload-avatar', [md_auth.authenticated, upload.single('file0')], UserController.uploadAvatar);

The final code related to this would look like this:

const multer = require('multer');

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './uploads/users/')
    },
    filename: function (req, file, cb) {
        cb(null, "user" + Date.now() + file.originalname);
    }
  });

const upload = multer({ storage: storage }); 

router.post('/upload-avatar', [md_auth.authenticated, upload.single('file0')], UserController.uploadAvatar);

It is also very important to highlight that the object of the uploaded file is attached to the request of the request, having to access it in this way: req.file o req.file.path to specifically access the path property we need.

Obviously in your routes file you must have more things, such as loading drivers, other middlewares, etc, but with these steps we have already solved this problem «Cannot read property ‘path’ of undefined» And the uploading of images would work, or any other type of file in node.

See you in the rest of my development courses, on this blog and on my YouTube channel 😉


Like it? Share with your friends!

0 Comments

Your email address will not be published. Required fields are marked *