【发布时间】:2021-10-13 07:46:18
【问题描述】:
我正在使用 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-aibhav-.-jpg-1628524045320.jpeg
现在,我想使用数据库中的图像 url 显示给客户端。但是,当我访问这个网址时,它会说:
无法获取 /public/uploadv-a-i-b-h-a-v-.-j-p-g-1628524045320.jpeg
如何将上传的图片显示给客户端?有没有其他方法可以做到这一点?
【问题讨论】:
-
你可以看到document关于在 Express 中提供静态文件
-
我已经这样做了
app.use(express.static('public/uploads'))。图片网址仍然无效。
标签: node.js reactjs express multer