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

使用Multer与React.js上传图片:后端存储正常但前端无法预览求助

图片上传后无法预览(404错误):静态资源路径配置排查

我使用Multer构建了图片上传API,图片已成功存储到本地文件夹,接口返回的图片路径也保存至MongoDB数据库,但在浏览器及前端页面均无法预览该图片,浏览器返回404状态码。怀疑是静态资源路径配置存在问题,但未排查出错误。相关代码及截图如下:

上传路由代码(upload router)

import express from "express";
import multer from "multer";
import path from "path";
import { Request, Response } from "express";
const router = express.Router();

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

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

router.post("/", upload.single("image"), (req: any, res: Response) => {
  const imgUrl = req.file.path.replace(/\\/g, "/");
  console.log(imgUrl);
  res.send(`/${imgUrl}`);
});

export default router;

服务器配置代码(server.js)

app.use("/api/v1/uploads", imageUpload);
app.use("/uploads", express.static(path.join(__dirname, "/uploads")));

前端上传处理逻辑

const uploadImgHandler = async (e: any) => {
    const file = e.target.files[0];
    const formData = new FormData();
    formData.append("image", file);
    setUploadingImg(true);

    try {
      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };

      const { data } = await axios.post(
        "http://localhost:5000/api/v1/uploads",
        formData,
        config
      );
      console.log("data", data);
      setEmployeeImg(data);
      setUploadingImg(false);
    } catch (error) {
      console.error(error);
      setUploadingImg(false);
    }
  };

前端上传输入组件(JSX)

<input
    accept="image/*"
    name="image"
    id="contained-button-file"
    type="file"
    style={{ padding: 10 }}
    onChange={uploadImgHandler}
/>

前端图片渲染代码(JSX)

<div>
    <p>Address: {profile?.address}</p>
    <p>Salary: {profile?.salary}</p>
    <p>Joinning Date: {profile?.joingDate}</p>
    <p>image</p>
    <img
      src={`http://localhost:5000/api/v1/uploads${profile?.image}`}
      alt=""
      style={{ height: "10rem", width: "10rem" }}
    />
</div>

存储的图片路径(profile.image 值)

存储的图片路径

浏览器预览截图

浏览器预览截图

本地存储的图片文件

本地存储的图片文件

浏览器404错误信息

浏览器404错误信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:45:34