user9358862
user9358862

Reputation:

Multer - Cannot Read Property "path" of Undefined

I'm trying to upload a single image to mongo using multer but I keep getting this error while trying to access the image path like:

TypeError: Cannot read property 'path' of undefined
at router.post (D:\Workspace\AdminBootstrap\routes\admin_index.js:74:29)

Here's my code to upload the image:

router.post('/add-category', uploads.single('category_image'), (req, res) => {

let title = req.body.title;
console.log('Category Title:\t' + title);
let slug = title.replace(/\s+/g, '-').toLowerCase();
let catImage = req.file.path; // error occurs here 

console.log(catImage);

let category = new Category({
    title: title,
    slug: slug,
    image: catImage
});

category.save()
    .then(result => {
        if (result) {
            console.log('Saved Category:\t' + result);
            res.redirect('/admin/home');
        }
    })
    .catch(errors => {
        console.error('Error Saving Category:\t' + errors);
    });


});

Here's my template:

<label>Upload Image</label>
                                <input name="category_image" class="form-control" type="file" accept="image/*" id="selImg"  onchange="showImage.call(this)">
                                <img src="#" id="imgPreview" style="display: none; height: 100px; width: 100px">

Can anyone explain to me why the path is throwing an error?

Upvotes: 0

Views: 8412

Answers (2)

Lukman Isiaka
Lukman Isiaka

Reputation: 71

While setting up your HTML, your form should have an attribute of enctype="multipart/form-data" This will save your file in the path variable

Upvotes: 0

Shahrukh Haider
Shahrukh Haider

Reputation: 474

The path is throwing an error because "file" is not defined inside "req" object. It is probably defined in "req.body" object. Use

console.log(req.body)

to confirm. Since title is defined on "req.body", "file.path" also should be defined on the same object.

Upvotes: 1

Related Questions