Search code examples
node.jsmongodbmongoosepugmulter

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


I have a form that takes image and text, save the image in uploads folder and save image path and the text in MongoDB database with mongoose.

My question is how do I get the uploaded image path?

My code:

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


Solution

  • You can get the data of the file you just uploaded with req.file , so to access the path of your file you can use req.file.path