You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MERN前端通过Multer显示MongoDB中的图片?

问题:前端无法展示Multer存储的MongoDB帖子图片

我通过GET请求从MongoDB获取帖子数据,使用Multer中间件完成图片存储,但前端无法展示图片。目前已通过/feed路由成功获取包含art_image字段的帖子数据,想请教img标签的src属性应如何填写才能正常显示图片。

后端代码(posts.js)

import express from "express";
import multer from "multer";
import Posts from "../models/posts.js";


const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({ storage: storage });

const router = express.Router();

router.route("/create").post(upload.single('file'), async (req,res)=>{
  try {
    const post = new Posts({
      title: req.body.title,
      description: req.body.description,
      amt: req.body.amt,
      artist_name: req.body.artist_name,
      
      art_image: req.file.filename,
    });

    const savedPodcast = await post.save();
    res.status(201).json(savedPodcast);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal server error" });
  }
});

router.route("/feed").get( async (req, res) => {
  try {
    const getPosts = await Posts.find();
    console.log(getPosts)
    res.json(getPosts);
   
  } catch (error) {
    res.status(500).json({ message: "Error fetching posts", error });
  }
});


export default router

获取到的帖子数据

[
  {
    _id: new ObjectId("6479438fdf4ff1fc5cf2eab8"),      
    artist_name: 'sad',
    title: 'gfds',
    description: 'adf',
    amt: '234',
    reportCount: 0,
    upvote: 0,
    createdAt: 2023-06-02T01:19:02.297Z,
    art_image: '1685668751687-event_juntion.png',       
    apply_watermark: true,
    __v: 0
  }
]

解决方案

1. 配置后端静态资源访问

当前后端没有将uploads文件夹暴露为静态资源,前端直接访问图片路径会返回404。需要在项目主入口文件(如app.js/server.js)中添加以下代码:

import express from "express";
const app = express();

// 将uploads文件夹设为静态资源目录,允许前端通过URL直接访问其中的文件
app.use('/uploads', express.static('uploads'));

2. 前端img标签的src写法

从/feed接口获取的art_image是图片文件名,需要拼接成后端服务地址 + /uploads/ + 文件名的完整路径:

  • 静态HTML示例:
<img src="http://localhost:3000/uploads/1685668751687-event_juntion.png" alt="帖子图片" />
  • React动态渲染示例:
{posts.map(post => (
  <img 
    key={post._id} 
    src={`http://localhost:3000/uploads/${post.art_image}`} 
    alt={post.title} 
  />
))}
  • Vue动态渲染示例:
<img 
  v-for="post in posts" 
  :key="post._id" 
  :src="`http://localhost:3000/uploads/${post.art_image}`" 
  :alt="post.title" 
/>

3. 注意事项

  • 确保项目根目录下的uploads文件夹存在,且具备读写权限
  • 部署到生产环境时,将http://localhost:3000替换为你的线上服务器域名(如https://your-domain.com)

内容的提问来源于stack exchange,提问作者Jayanti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 02:45:27