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?