I am working on a blogging application (click the link to see the GitHub repo) with Express , EJS and MongoDB.
I am trying to introduce an add post image feature with Multer. Being quite new to Express, I run into trouble.
In utils\imageupload.js
I have added:
const multer = require("multer");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/images')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + '.png')
}
});
exports.upload = multer({ storage: storage }).single('postimage');
I import and use that in my dashboard routes file:
const imageUploader = require('../../utils/validation.js');
//more code
// Add Post
router.post('/post/add', imageUploader.upload, validator.addPostCheck, dashboardController.addPost);
//more code
In the controller I have (among others):
exports.addPost = (req, res, next) => {
upload(req, res, function(err) {
if (err) {
console.log("There was an error uploading the image.");
} else {
res.sendStatus(200);
}
})
var form = {
titleholder: req.body.title,
excerptholder: req.body.excerpt,
bodyholder: req.body.body
};
const errors = validationResult(req);
const post = new Post();
post.title = req.body.title;
post.short_description = req.body.excerpt
post.full_text = req.body.body;
if (!errors.isEmpty()) {
req.flash('danger', errors.array())
res.render('admin/addpost', {
layout: 'admin/layout',
website_name: 'MEAN Blog',
page_heading: 'Dashboard',
page_subheading: 'Add New Post',
form: form
});
} else {
post.save(function(err) {
if (err) {
console.log(err);
return;
} else {
req.flash('success', "The post was successfully added");
req.session.save(() => res.redirect('/dashboard'));
}
});
}
}
As long as the line imageUploader.upload
is in the controller, the entire application just crashes, with the error: Route.post() requires a callback function but got a [object Undefined] error
.
What am I doing wrong?
You have the following line:
const imageUploader = require('../../utils/validation.js');
validation.js
does not export upload
which you are using here:
// Add Post
router.post('/post/add', imageUploader.upload, validator.addPostCheck, dashboardController.addPost);
Changing the import to
const imageUploader = require('../../utils/imageupload.js');
should fix the problem.
Regarding the problem in the admin dashboard-controller: Since you've already called the multer upload, you can remove it in addPost
, req
should now contain the uploaded file.
exports.addPost = (req, res, next) => {
// removed the upload code
var form = {
titleholder: req.body.title,
excerptholder: req.body.excerpt,
bodyholder: req.body.body
};
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.