我使用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>

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

enter image description here

browser screenshot enter image description here

存储在我的文件夹中的图像

enter image description here

也许我在什么地方弄错了,但找不到.但我认为,静态路径有问题.但我没有发现任何问题.

In the browser, the error is as the bellow enter image description here

推荐答案

您可以try 以下操作:

   //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>

Node.js相关问答推荐

NX无法使用缓存运行根级脚本

MongoDB:更新批量操作中许多不能正常工作的内容

如何将我的Redis客户端配置为在禁用群集模式的情况下使用读取副本?

在 Docker 容器内创建一个 cron 作业(job)来执行 run.js 文件中的函数

无法截取页面截图

未捕获的错误: 只能用作 元素的子元素,永远不会直接呈现.请将您的 包裹在

Cloudflare 522 错误 - javascript 客户端连接到 node 服务器

结合后端(Express)和前端(Angular)路由

Jest - SyntaxError: 不能在@nestjs/axios 的模块外使用 import 语句

Typescript typeRoots 未检测到类型定义

处理 UTC 日期和future

Firestore promise 在退货前等待产品详细信息

这到底是什么';拒绝未经授权';对我来说是什么意思?

AWS Kinesis 中的分区键是什么?

JSHint 是否支持异步/等待?

如何在不全局安装的情况下在 Node REPL 中要求 node 模块?

处理快速异步中间件中的错误

在 Node.js 中获取终端的宽度

什么时候应该将函数存储到变量中?

避免在弹性 beantalk 中重建 node_modules