图像存储在后端文件夹中,但使用multer和react.js在前端找不到

问题描述 投票:0回答:2

我使用 Multer 创建了一个图像上传 API。该图像也存储在我的文件中并响应回图像的路径。但我无法在浏览器和前端预览此图像。

我将图像保存在本地文件夹中,并获得作为图像路径的响应。我将路径保存在 MongoDB 数据库中,并想从数据库中获取图像。

//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")));
//image input
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);
    }
  };
// input jsx
 <input
            accept="image/*"
            name="image"
            id="contained-button-file"
            type="file"
            style={{ padding: 10 }}
            onChange={uploadImgHandler}
          />
//fetch image
 <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>

图像路径/配置文件.图像值

浏览器截图

图像存储在我的文件夹中

也许我在某个地方犯了错误,但找不到。但我认为静态路径有问题。但我没发现什么不妥的地方。

在浏览器中,错误如下

node.js reactjs file-upload multer
2个回答
1
投票

你可以试试这个:

   //server.js
        const dirname = path.resolve();
        app.use('/uploads', express.static(path.join(dirname, '/uploads')));


//fetch image
              <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${profile?.image}`}
                    alt=""
                    style={{ height: "10rem", width: "10rem" }}
                  />
                </div>

0
投票

上面的这个对我来说真的很有效!非常感谢你

© www.soinside.com 2019 - 2024. All rights reserved.