question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Multer req.file.path "Cannot read property 'path' of undefined"

See original GitHub issue

I’m new to node.js and try to built a simple REST Api with file uploading capabilities. For file upload I’m using multer from npm and using POSTMAN for sending post request. But when I try to upload file with multer I got this error:

{
    "error": {
        "message": "Cannot read property 'path' of undefined"
    }
}

Here is my code for the API

product.js

import express from 'express';
import mongoose from 'mongoose';
import Product from '../models/product.model';
import multer from 'multer';
import multipart from 'connect-multiparty';

const router = express.Router();

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './uploads');
    },
    filename: (req, file, cb) => {
        cb(null, `${new Date().toISOString().replace(/:/g, '-')}${file.originalname}`);
    }
});

const fileFilter = (req, file, cb) => {
    // reject a file
    if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        cb(null, false);
    } else {
        cb(new Error('Only .jpeg or .png files are accepted'), true);   
    }
};

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 5
    },
    fileFilter: fileFilter
});

router.post('/', upload.single('productImage'), (req, res, next) => {
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price,
        productImage: req.file.path
    });
    product.save().then(result => {
        console.log(result);
        res.status(201).json({
            message: 'Created product successfully',
            createdProduct: {
                name: result.name,
                price: result.price,
                _id: result._id,
                request: {
                    type: 'GET',
                    url: `http://localhost:3000/products/${result._id}`
                }
            }
        });
    }).catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
});

product.model.js

import mongoose from 'mongoose';

const productSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {type: String, required: true},
    price: {type: Number, required: true},
    productImage: { type: String, required: false }
});

module.exports = mongoose.model('Product', productSchema);

Even I use connect-multipart middleware to fix the issue but then I got other error:

{
    "error": {
        "message": "stream ended unexpectedly"
    }
}

Here is the code when use multipart

router.post('/', upload.single('productImage'), multipart(), (req, res, next) => {
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price,
        productImage: req.file.path
    });
    product.save().then(result => {
        console.log(result);
        res.status(201).json({
            message: 'Created product successfully',
            createdProduct: {
                name: result.name,
                price: result.price,
                _id: result._id,
                request: {
                    type: 'GET',
                    url: `http://localhost:3000/products/${result._id}`
                }
            }
        });
    }).catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
});

Now can anyone help me to fix this. It’s really a big problem for me to go ahead without solving the issue…

Thanks in advance.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

20reactions
LinusUcommented, Feb 12, 2018

The error message is telling you that req.file is undefined. That means that multer doesn’t think that it received a file.

How are you sending the file in Postman?

(also, I would recommend guarding against this with a if (!req.file) return res.send('Please upload a file'), that way your server won’t crash if someone calls the API without giving a file.

17reactions
MiguelCedriccommented, Mar 14, 2018

Hi, try setting your form enctype to multipart/form-data: <form method="post" id="add-product-form" action="/admin/products/add-product" enctype="multipart/form-data">

Read more comments on GitHub >

github_iconTop Results From Across the Web

node.js - Multer - Cannot Read Property "path" of Undefined
The path is throwing an error because "file" is not defined inside "req" object. It is probably defined in "req.body" object. Use.
Read more >
Cannot read property 'path' of undefined - Cloudinary Support
I'm getting this error even though multer logged the correct req.file. [0] req.file: {“fieldname”:“src”,“originalname”:“Pexels Videos...
Read more >
cannot read properties of undefined (reading 'path') multer ...
1. There could be a problem in the filename you give the file, causing multer to fail and not attaching the file property...
Read more >
Multer Error: TypeError: Cannot read property 'originalname' of ...
diskStorage({ destination: function (req, file, cb) { console.log(LOGO_PATH); cb(null, path.join(__dirname, '..', LOGO_PATH)); }, filename: ...
Read more >
How to solve "can not read property path of undefined" in ...
With upload.single() , the filename is in req.file . That's a string that represents the filename. There is no property req.file.path .
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found