【问题标题】:Cannot GET image url multer (NodeJS)无法获取图像 url multer (NodeJS)
【发布时间】: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


【解决方案1】:

正如你提到的图片上传成功在公共文件夹中。

那么这意味着我认为您还没有在快递中提供公用文件夹。

app.use('/public',express.static('public'))

在您的快速路由代码之前添加上述代码以使其工作。

请查看express static doc link

现在您可以访问公用文件夹了。

【讨论】:

  • 我已经这样做了app.use(express.static('public/uploads'))。图片网址仍然无效。
猜你喜欢
  • 1970-01-01
  • 2020-03-19
  • 2021-02-25
  • 2020-10-20
  • 2021-05-03
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多