使用Formidable上传Node.js文件-事件未触发

时间:2019-01-18 10:34:53

标签: node.js express file-upload formidable

我正在尝试使用Node.js和Formidable模块上传文件。

npm install formidable

然后我做完了,请阅读注释-在这里我可以解释每个函数的作用并描述算法:

// get access to the files that were sent;
// at this time I don't want the files to be uploaded yet;
// in the next function I will validate those files.
function form_parse() {
    form.parse(req, (err, fields, files) => {
      if (err) return req.Cast.error(err);
      if (Object.keys(files).length==0) return req.Cast.badRequest();
      req.files = files;
      return validate_files();
    });
  }

  // I made an object with options to validate against the
  // files. it works and continues to the process_files()
  // function only whether files are verified.
  function validate_files() {
    let limitations = require('../uploads-limitations');
    try {
      limitation = limitations[req.params.resource];
    } catch(err) {
      return req.Cast.error(err);
    }
    let validateFiles = require('../services/validate-files');
    validateFiles(req, limitation, err => {
      if (err) return req.Cast.badRequest(err);
      return process_files();
    });
  }

  // here is the problem - form.on doesn't get fired.
  // This is the time I want to save those files - after
  // fully verified
  function process_files() {
    form.on('file', function(name, file) {
      console.log(`file name: ${file.name}`);
      file.path = path.join(__dirname, '../tmp_uploads/' + file.name);
    });
    form.on('error', err => {
      return req.Cast.error(err);
    });
    form.on('end', () => {
      console.log(`successfully saved`);
      return req.Cast.ok();
    });
  }

  form_parse();

如您所见,正如我所描述的那样,验证有效,但是当我想实际保存这些文件时, form.on (事件)不会被触发。

1 个答案:

答案 0 :(得分:2)

是的,因为在处理的最后,在解析和验证之后,您将附加事件侦听器。在开始解析之前,应该先完成此操作。因为这些事件(在文件中,在错误中,在结束时)发生在解析期间,而不是之后。

 form.on('file',...) // First, attach your listeners
    .on('error', ...)
    .on('end', ...);

form.parse(req) // then start the parsing