I am currently in the process of redesigning a website, specifically the Blog section which includes a featured image. I have been researching the best method for saving these images.
After following a tutorial that utilized the file.mv() function from either mongoose or express (I believe), I was able to successfully move the images to a folder within my public directory while working on the development server. However, upon deploying to Heroku, the functionality ceased to work, likely due to file path inconsistencies.
I'm not certain if my approach is considered conventional, but essentially I allow blog writers to upload an image along with their post. The post content is then saved to my MongoDB database, with the file location stored under the featured image field rather than the entire image itself. This bypasses the need to store the image directly in the database.
If anyone has any advice on how to resolve this issue, it would be greatly appreciated! Thank you!
Below is the code snippet:
//save images
blogRouter.post('/upload', (req, res) => {
if(req.files === null ){
return res.status(400).json({ msg: 'No file uploaded'})
}
const file = req.files.file;
const fileName = file.name.replace(/\s+/g, '');
file.mv(`${__dirname}/../client/public/BlogImgs/${fileName}`, err => {
if(err){
console.error(err)
return res.status(500).send(err);
}
res.json({ fileName: fileName, filePath: `/BlogImgs/${fileName}`});
})
})
//Post New Blog
blogRouter.post('/', (req, res) => {
let newBlog = new blog({
title: req.body.title,
content: req.body.content,
author: req.body.author,
comments: req.body.comments,
featuredImg: req.body.featuredImg,
summary: req.body.summary
})
newBlog.save().then(item => res.json(item))
})