【问题标题】:How to upload and retrieve images in mognoose with multer file references如何使用 multer 文件引用在 mognoose 中上传和检索图像
【发布时间】:2021-03-21 00:42:47
【问题描述】:

我正在尝试以 django 风格的方式保存图像,其中图像被保存到文件夹中,文件的路径在获取请求中返回。

到目前为止,我有以下图片模型:

const PictureSchema = new mongoose.Schema(
  {
    image: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model("Picture", PictureSchema);

以及以下观点:

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "data/images");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + ".jpg");
  },
});

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

app.post("/upload", upload.single("image"), (req, res) => {
  Picture.create({
    image: req.file.path,
  })
    .then((picture) => res.status(201).json(picture))
    .catch((err) => res.status(500).json({ error: err.message }));
});

app.get("/", (req, res) => {
  Picture.find({}, "-__v")
    .then((pictures) => res.status(200).json(pictures))
    .catch((err) => res.status(500).json({ error: err.message }));
});

一切正常,文件被保存到一个文件夹中,当我检索它时显示如下:

{
    "_id": "5fd0f1d4f81e3f28b0aa70d3",
    "image": "data\\images\\1607528916952.jpg",
    "createdAt": "2020-12-09T15:48:36.967Z",
    "updatedAt": "2020-12-09T15:48:36.967Z",
    "__v": 0
}

但我已经明确设置为静态目录,例如:

app.use(express.static("data"));

我如何让它返回带有图像字段的相对路径而不是文件系统内的相对路径的实例?

【问题讨论】:

    标签: node.js mongodb express mongoose multer


    【解决方案1】:

    由于您已将 data 目录定义为静态服务,因此您需要使用以下 url 请求图像:

    http://<yourHost>:<yourPort>/images/160...44.jpg
    

    如果你想改变这个并且只指定图片的名字,你需要调整你传递给express.static中间件的路径:

    app.use(express.static("data/images"));
    

    现在您可以使用以下网址请求图片:

    http://<yourHost>:<yourPort>/160...44.jpg
    

    【讨论】:

      猜你喜欢
      • 2017-07-04
      • 2023-01-07
      • 2021-11-23
      • 2019-12-05
      • 2022-01-10
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 2017-04-14
      相关资源
      最近更新 更多