Reputation: 33
multer.js
var path = require("path"),
multer = require("multer");
const storage = multer.diskStorage({
destination: function(req, file, next){
next(null, '../public/imgs/');
return;
},
filename: function(req, file, cb){
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({
storage: storage
});
module.exports = upload;
router.js
//handle createPartner route
router.post("/partner/new", upload.single('image'), function(req, res){
console.log(req.file);
console.log(req.body);
req.body.Partner["image"] ="/static/imgs/"+req.file.filename;
req.body.Partner.body = req.sanitize(req.body.Partner.body);
Partner.create(req.body.Partner, function(err, createdPartner){
if(err){
console.log(err);
res.redirect("/admin/partner/new");
}else{
res.redirect("/partners");
}
});
});
I get the following console.log
{ fieldname: 'image',
originalname: 'fb.png',
encoding: '7bit',
mimetype: 'image/png',
destination: '../public/imgs/',
filename: 'image-1521727739861.png',
path: '../public/imgs/image-1521727739861.png',
size: 21532 }
{ Partner: { name: 'test', bio: 'test', image: '', website: 'test' } }
so multer does get the file but it doesn't upload it to the destination! The permissions for /public and /public/imgs are 777. Everywhere I searched uses the other method for multer but that way I'll have to specify (single/multiple/any) in advance which isn't right.
Upvotes: 1
Views: 393
Reputation: 9283
You need to include the absolute path as I mentioned in comments.
You can easily do this by utilising path.join
like follows:
var path = require('path');
var dir = path.join(__dirname, '../public/imgs')
That will concatenate __dirname
which is the absolute path of the current file with your images file.
Upvotes: 1