如何从带有 multer 的表单中获取上传文件的路径

how do I get the path of the uploaded file from a form with multer

我有一个获取图像和文本的表单,将图像保存在上传文件夹中,并使用 mongoose 将图像路径和文本保存在 MongoDB 数据库中。

我的问题是如何获取上传的图片路径?

我的代码:

// the router

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


router.post('/add', upload.single('image'),function (req, res, next) {
  let image = new Image();
  image.path = file.path;
  image.text = req.body.text;

  image.save(function (err) {
    if (err) {throw err;}
    else {
      req.flash('success', 'File uploaded');
      res.redirect('/media/add');
    }
  });
});


// the pug file

extends layout.pug

block css

block content
  if user&&user.roles==admin
      h1 add image to gallery
      form(method='POST', action='/media/add', enctype="multipart/form-data")
        .form-group
          label Image path:
          input.form-control(name='image', type='file')
        .form-group
          label Title:
          input.form-control(name='text', type='text')  

        input.btn.btn-primary(type='submit', value='Add')

  else
    p not have accsess

您可以使用 req.file 获取刚刚上传的文件的数据,因此要访问您的文件路径,您可以使用 req.file.path