I have a website that I am rewriting. The Blog area of the website has a featured image - and I am trying to figure out the best way to go about saving the images.
I followed a tutorial that uses the file.mv() function from mongoose (I think from mongoose? Maybe express?) - Either way, it moves the images to a folder inside my public folder.
It works on the dev server but, when I push to Heroku, it does not. I am sure it has something to do with file locations.
I don't know if I am doing this in a traditional way... But Basically I let the blog writer upload the picture and write the post. Then I saved the post content to my bongo db. The file location was saved under the featured image instead of the whole picture being saved under the featured image. That way I didn't have to upload the image to a DB.
Any advice is welcome! Thank!
Here is the code
//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))
})
you don't need to store it in your DB just store its name and have the image itself in a folder on your server, you can use multer for image uploading.
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.