我使用multer
库在我的React/NodeJS网站上上传文件。
这是后端的上传路径:
var upload = multer({storage});
router.post('/events/upload', upload.single('image'), async (req, res) => {
try {
const fileName =req.file.filename;
const basePath = `${req.protocol}://${req.get('host')}/public/upload`
let event = new Event({
title: req.body.title,
description: req.body.description,
image: `${basePath}${fileName}`
})
event = await event.save()
if (!event) {
return res.status(400).send("Error in upload!")
}
return res.status(200).send(event)
} catch(error) {
console.log(error)
return res.status(500).send()
}
})
点击此端点后,图像成功上传到public/uploads
,生成的"url"如下- http://localhost:5000/public/uploadv-a-i-b-h-a-v-.-j-p-g-1628524045320.jpeg
现在,我想使用数据库中的图像url来显示给客户端。但是,当我访问这个url时它显示:
无法GET/public/uploadad -a-i-b-h-a-v-.-j-p-g-1628524045320.jpeg
如何将上传的图片显示到客户端?还有其他方法可以做到这一点吗?
正如您所提到的,图像在公共文件夹中上传成功。
我想这意味着你没有在express中提供公共文件夹。
app.use('/public',express.static('public'))
在您的快递路由代码之前添加上述代码以使其工作。
请查看此快速静态文档链接。
现在你可以访问公共文件夹了。