I am trying to use multer to upload an image to a mysql database , and I am getting an error stating
TypeError: Cannot read property 'path' of undefined
my App.js
var multer = require('multer');
app.use(express.static("public"));
app.post("/updateImage/add",multer({ dest: './public/uploads/'}).single('img') ,contentUpdate.addImage);
my contentUpdate.js
exports.addImage = function(req, res) {
var path = (req.file.path).replace("public/", '');
console.log(path);
var data =
{
image: path
};
var URLs = data.PageURL;
connection.query('INSERT INTO `updatedimages` SET ?', [data], function(err, rows)
{
if (err)
{
console.log(err);
} else
{
req.flash('success','Entry Successful');
return res.redirect(URLs);
}
});
};
my updateImage.handlebars
<form id="myForm" action='/updateImage/add' method='POST' >
<div class="col-md-12" >
<input name='img' type="file" class="form-control" required/>
</div>
<div>
<button type="submit" class="glyphicon glyphicon-submit btn btn-primary ">
</div>
You need to set the proper encoding type in the HTML:
<form id="myForm" action='/updateImage/add' method='POST' enctype='multipart/form-data'>
Even so, it's always good to also validate the input:
if (! req.file || ! req.file.path) {
return res.sendStatus(400);
}