【问题标题】:To use multer to save files in different folders?要使用 multer 将文件保存在不同的文件夹中?
【发布时间】:2018-07-28 06:17:18
【问题描述】:

我在 express 中使用 multer 进行文件存储,但是当我在文件中使用 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};

这是我参加活动的路线

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

这是上传路径

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

甚至 req.params 在 multer 中也是空的

【问题讨论】:

  • 您在哪里使用 multer 中间件?
  • 我正在使用 multer 将图像文件上传到服务器。
  • 但是你必须在路由中使用它,比如:app.get('/event/:event', multer({}), (req, res) => {})
  • 尝试使用 url 使用 multer 对文件夹中的图像进行分类
  • 你在你的 GitHub 中有 '/events/upload' 路由 upload(req,res,function(err) {}) - 这是你的问题中缺少的。

标签: node.js express url multer


【解决方案1】:
                Quit late for this answer, but maybe it will help to someone

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

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

您可以在此处查看 req.body :

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

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

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

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);
  }
});

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

正如你在图片中看到的,事件键放在图片键之前

现在它将检测正文并能够将文件上传到不同的文件夹中进行测试,并按照示例代码进行尝试。

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 2021-07-15
    • 2016-10-18
    • 2021-11-18
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2018-11-11
    相关资源
    最近更新 更多