【问题标题】:Retrieving req.body with connect-busboy使用 connect-busboy 检索 req.body
【发布时间】:2014-07-30 11:54:12
【问题描述】:

发布多部分表单时,我可以使用 connect-busboy 检索文件,但无法从 req.body 获取值。我假设我需要挂钩 req.busboy.on('field'),但不知道将其放置在哪里,以便我仍然可以利用当前正在处理上传文件的功能。


routes.js

var busboy = require('connect-busboy');

module.exports = function (app) {
  app.use(busboy());
  app.route('/upload')
    .post(function (req, res) {
      req.pipe(req.busboy);
      upload.createImg(req, res);
    });

upload.js

var fs = require('fs');

exports.createImg = function (req, res) {
  var fstream,
      path = './uploads/temp/';

  req.busboy.on('file', function (fieldname, file, filename) {
    fstream = fs.createWriteStream(path + filename);
    file.pipe(fstream);
    fstream.on('close', function() {
      fs.readFile(path + filename, function (err, data) {
        // need help here
      });
    });
  });
});

在上面的代码示例中,我能够检索上传的文件,然后我可以使用 ImageMagick 成功操作这些文件。然而,问题是我想从 req.body 中检索数据,例如 req.heightreq.width 等。不过,似乎 busboy 还没有完成它的魔力,因为 req.bodyundefined

如何将req.body 传递给fstream.on('close', ...) 中的函数?

【问题讨论】:

    标签: node.js file-upload express multipartform-data


    【解决方案1】:

    如果您想要/期望多方/强大风格的 API 但使用 busboy,您应该查看 multer

    【讨论】:

    • 这个添加的层正是我所需要的。谢谢。
    【解决方案2】:

    你可以使用这个 busboy field 事件来获取解析数据 -

    req.busboy.on('field', function(fieldname, val) {
        console.log(fieldname, val);
    });
    

    【讨论】:

      【解决方案3】:

      收听filefieldfinish 事件。 finish 事件将在解析表单后触发。您可以使用filefield 事件来缓存信息,并在处理完filefield 事件后在finish 事件中使用它们进行后期处理。如果您收听file 事件,请记住处理流。否则不会触发其余事件。 Read BusBoy Docs Here.

      例如,

      app.post('/upload', (req, res) => {
      
          let uploadedFileName = null;
          let userId = null;
      
          req.busboy.on('file', (fieldName, file, fileName) => {
      
              let uploadPath = path.join(__dirname, 'public', fileName);    
              uploadedFileName = fileName; // let's store this to use in finish event
      
              let stream = fs.createWriteStream(uploadPath);
              // file stream is consumed here. If it's not consumed, finish event wont trigger.
              file.pipe(stream); 
          });
      
          req.busboy.on('field', (fieldName, val) => {
              if (fieldName == 'userId') {
                  userId = val; //cache some more fields
              }
          })
      
          req.busboy.on('finish', () => {
      
              // You can access both values and both above event handles have run before this handler.
              console.log(userId, uploadedFileName);
      
              
          })
      
      
          req.pipe(req.busboy);
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-27
        • 2014-06-30
        • 2023-03-05
        • 2015-11-17
        • 1970-01-01
        • 2017-05-15
        • 2021-06-02
        • 2020-11-18
        相关资源
        最近更新 更多