【发布时间】:2019-06-12 14:39:18
【问题描述】:
我正在尝试使用 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(事件)不会被触发。
【问题讨论】:
-
是的,因为在您的流程结束时,在解析和验证之后,您附加了事件侦听器。这应该首先完成,在开始解析之前。因为这些事件(存档、错误、结束)发生在解析期间,而不是之后。
-
我怎样才能让它正常工作?
-
我已经添加了完整的答案。
标签: node.js express file-upload formidable