【发布时间】:2020-06-08 13:02:50
【问题描述】:
我有一个正在重写的网站。网站的博客区域有一张特色图片 - 我正在尝试找出保存图片的最佳方法。
我遵循了一个使用 mongoose 中的 file.mv() 函数的教程(我认为来自 mongoose?也许是快递?) - 无论哪种方式,它都会将图像移动到我的公共文件夹内的文件夹中。
它可以在开发服务器上运行,但是当我推送到 Heroku 时,它就不行了。我确信这与文件位置有关。
我不知道我是否以传统方式这样做......但基本上我让博客作者上传图片并写帖子。然后我将帖子内容保存到我的 bongo db。文件位置保存在特色图像下,而不是整个图片保存在特色图像下。这样我就不必将图像上传到数据库。
欢迎任何建议!谢谢!
这里是代码
//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))
})
【问题讨论】:
标签: javascript image api express