使用 multer 将文件保存在不同的文件夹中?

Alp*_*and 3 url node.js express multer

我使用 multer 在 Express 中进行文件存储,但是当我在文件中使用 req.params.event 时,我得到了未定义。为什么会出现这种情况。没有 req.params.event 我无法对文件夹中的上传进行分类

  var multer = require('multer');


var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        console.log(req.params.event);  //This console log is undefined
        callback(null, './uploads');
    },
    filename: function (req, file, callback) {
        callback(null, file.fieldname + '-' + Date.now());
    }
});

   var upload= multer({
        storage: storage
    }).single('userPhoto');

module.exports={upload:upload};
Run Code Online (Sandbox Code Playgroud)

这是我参加活动的路线

 app.get('/events/:event', (req, res) => {
      console.log(req.params.event); // here working perfectly
    res.render('event.hbs', {
    });
})
Run Code Online (Sandbox Code Playgroud)

这是上传路径

    app.post('/events/upload',upload,function(req,res){
  console.log("uploded")
});
Run Code Online (Sandbox Code Playgroud)

即使 req.params 在 multer 中也是空的

Ama*_*pta 7

                Quit late for this answer, but maybe it will help to someone
Run Code Online (Sandbox Code Playgroud)

当使用 multer 上传文件时,请求对象的参数和查询不会在文件之前填充,因此您无法在上传文件之前访问它,就像您在 multer.diskStorage 下的情况一样。

类似的 req.body 在上传文件之前可能尚未完全填充。这取决于客户端向服务器传输字段和文件的顺序。

你可以在这里检查 req.body :

https://github.com/expressjs/multer#diskstorage

现在回答使用 multer 将文件保存在不同的文件夹下:

1)首先你应该使用req.body.event对文件夹进行分类,即使用body而不是使用query和params来传输事件

2)现在,在从客户端发布文件期间,颠倒事件和文件的顺序,即先发布事件,然后发布文件

您可以参考这段对我来说效果很好的代码

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    if (req.body.event == 'test') {
      cb(null, "images/test"); // it will upload inside test under images
    } else {
      cb(null, "images/try"); // it will upload inside try under images
    }
  },
  filename: (req, file, cb) => {
    cb(null, new Date().toISOString() + "-" + file.originalname);
  }
});
Run Code Online (Sandbox Code Playgroud)

现在从客户端说使用邮递员:

在此输入图像描述

如图所示,事件键位于图像键之前

现在它将检测正文,并能够将文件上传到不同的文件夹测试并尝试,如示例代码所示。