簡體   English   中英

使用Formidable上傳Node.js文件-事件未觸發

[英]Node.js file uploading using Formidable - events are not getting fired

我正在嘗試使用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 (事件)不會被觸發。

是的,因為在處理結束時,在解析和驗證之后,您將附加事件偵聽器。 在開始解析之前,應該先完成此操作。 因為這些事件(在文件中,在錯誤中,在結束時)發生在解析期間,而不是之后。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM