使用Multer存储图像,并将路径仅存储在MongoDB中

时间:2020-07-10 10:52:55

标签: node.js mongodb express multer

所以我的架构的一部分看起来像这样photo: [{data: Buffer, contentType: String }]

Multer像这样存储图像:

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/uploads');
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  }
});
app.use(multer({
  storage: storage
}).single('photo'));

现在我知道它将图像存储为Mongodb中的缓冲区,并将文件也存储在服务器上。我希望它将文件路径存储在数据库中,然后将其实际图像文件存储在服务器上。它将图像存储为似乎是文本文件,并以utf-8编码。对于看似简单的任务(存储图像),这是一个非常复杂的过程

1 个答案:

答案 0 :(得分:0)

您可以使用req.file.path

访问文件的路径
app.post("/file", function(req, res) {
  console.log(req.file.path)
})