【问题标题】:how do I get the path of the uploaded file from a form with multer如何使用 multer 从表单中获取上传文件的路径
【发布时间】:2019-10-23 18:22:42
【问题描述】:

我有一个带有图像和文本的表单,将图像保存在上传文件夹中,并将图像路径和文本保存在 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

【问题讨论】:

    标签: node.js mongodb mongoose pug multer


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-10
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      相关资源
      最近更新 更多