Reputation: 33
I added multer to my node js app and it works fine, just the path of the image which I need to store in db isn't correct. Can't find the problem, its obviously some stupid mistake made by me.
This is my setup for multer
const multer = require('multer');
const storage = multer.diskStorage({
destination: './public/images',
filename: function(req, file, next){
next(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage: storage});
Here is how I use it to store the path
router.post('/add', upload.single('myImage'), function(req, res){
req.checkBody('title','Title is required').notEmpty();
//req.checkBody('author','Author is required').notEmpty();
req.checkBody('body','Body is required').notEmpty();
// Get Errors
let errors = req.validationErrors();
if(errors){
res.render('add_article', {
title:'Add Article',
errors:errors
});
} else {
let article = new Article();
//var date = new Date();
article.title = req.body.title;
article.author = req.user._id;
article.body = req.body.body;
article.descript = req.body.descript;
article.category = req.body.category;
article.date = getDate();
article.time = getTime();
article.comments = 0;
article.img = req.file.path;
console.log(req.file);
article.save(function(err){
if(err){
console.log(err);
return;
} else {
req.flash('success','Article Added');
res.redirect('/');
}
});
}
});
You can see from here that the path isnt right and I can't use it on GET
{ _id: 5bd993756373a5182460aa2a,
title: 'Sport 5',
author: '5acab056708e0d1248cba6ed',
body: 'sadddddddddddddd213',
descript: 'dsadas',
category: 'sport',
date: '2018/10/31',
time: '12:35',
comments: 0,
img: 'public\\images\\1540985717747-nike_logo_slogan_sport_advertising_42643_1280x1024.jpg',
__v: 0 }
Upvotes: 3
Views: 2741
Reputation: 9
This happens in windows because any file path in windows has back slash only but to make the file accessible through url it has to have front slash. So just use the below code to convert all backslash to front slash
const imageUrl = req.file.path.replace("\", "/");
Upvotes: 0
Reputation: 608
Multer is working correctly on your end you just need to convert the system path into a url accessible one.
Here this will help you.
article.comments = 0;
let fileUrl = req.file.path.replace(/\\/g, "/").substring("public".length);
article.img = fileUrl;
Upvotes: 2