【问题标题】:How to pass data from one router to another in ExpressJS and multer?如何在 ExpressJS 和 multer 中将数据从一个路由器传递到另一个路由器?
【发布时间】:2017-03-12 16:53:46
【问题描述】:

我有以下代码:

router.use('/', function (req, res, next) {
  var token = req.headers['authorization'];
  jwt.verify(token, config.secret, function (err, decoded) {
    if (err) {
      return res.json({
        success: false,
        message: 'Failed to authenticate',
        error: err
      });
    } else {
      req.decoded = decoded;
    }
    next();
  });
})

var _storage = multer.diskStorage({
  destination: function (req, file, cb) {
    var dest = './express-server/uploads/users/'  + req.decoded.user._id;
    var stat = null;
    try {
      stat = fs.statSync(dest);
    }
    catch (err) {
      fs.mkdirSync(dest);
    }
    if (stat && !stat.isDirectory()) {
      throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"');
    }
    cb(null, dest )
  },
  filename: function (req, file, cb) {
    crypto.pseudoRandomBytes(2, function (err, raw) {
      cb(null, raw.toString('hex') + '.' + file.originalname.toLowerCase());
    });
  }
});  

var upload = multer({storage: _storage});
imageType = upload.single('fileUpload');

router.post('/upload', imageType, function (req, res, next) {
  console.log(req.file.path)  // this logs out the path
  res.send({success:true);
});

到目前为止一切顺利,图片从前端上传并正确存储在文件系统中。

在这条路线的正下方,我有另一条路线:

router.post('/new', function ( req, res,  next) {
  var token = req.headers['authorization'];
  var decoded = jwt.decode(token);
  User.findById(decoded.user._id, function (err, doc) {
    if (err) {
      return res.status(404).json({
        title: 'An error occured',
        err: err
      });
    }

    var person = new Person({
      name: req.body.name,
      lastName: req.body.lastName,
      imageURL: **// how i can grab the uploaded file path inside this route from the upload route? Is this even possible?**,
      user: doc
    })

在这段代码之后,我将表单保存在 Mongodb 中没有任何问题,我只是无法获取文件名路径。

Person.save(function (err, newPerson) {
      if (err) {
        return res.status(404).json({
          title: 'An error occured',
          err: err
        });
      }
      doc.person.push(newPerson);
      doc.save();
      res.status(200).json({
        message: 'Person Saved!',
        obj: newPerson
      });
    });
  });
});

有什么想法吗?

【问题讨论】:

    标签: node.js mongodb express mongoose multer


    【解决方案1】:

    如果您的中间件或路由处理程序中有一个正常工作的图像保存步骤,最好将上传文件的公共 URL 添加到用户对象以供以后保存。

    我强烈建议不要使用建议将整个图像作为缓冲区存储在数据库中的方法。虽然这是可能的,但它会给您的服务器带来比从磁盘发送静态文件更多的负载,并且静态文件处理(例如 CDN)的低成本选项,如果您存储在一个分贝。

    【讨论】:

      【解决方案2】:

      无法获取使用当前设置上传的文件。

      如果我是你,我会做的是将用户上传的内容也保存在数据库中。

      router.post('/upload', imageType, function (req, res, next) {
      
        User.findById(req.decoded.user._id, function (err, doc) {
          if (err) { return res.status(500).send("Internal server error") }
          doc.file = req.file;
          doc.save( function( err ) { res.send( { success: true } ) }
        } );
      
      });
      

      然后在你的路线中

      router.post('/new', function ( req, res,  next) {
        var token = req.headers['authorization'];
        var decoded = jwt.decode(token);
        User.findById(decoded.user._id, function (err, doc) {
          if (err) {
            return res.status(404).json({
              title: 'An error occured',
              err: err
            });
          }
      
          var person = new Person({
            name: req.body.name,
            lastName: req.body.lastName,
            imageURL: doc.file.path
            user: doc
          });
      } );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-22
        • 1970-01-01
        • 2017-08-16
        • 2020-11-26
        • 1970-01-01
        相关资源
        最近更新 更多