我正在尝试做一个文件上传使用Node.js和强大的模块。
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 (事件)不会被触发。
发布于 2019-01-18 10:46:35
是的,因为在流程结束时,在解析和验证之后,您会附加事件侦听器。在开始解析之前,应该先这样做。因为这些事件(文件上、错误上、最后)都是在解析过程中发生的,而不是在解析之后。
form.on('file',...) // First, attach your listeners
.on('error', ...)
.on('end', ...);
form.parse(req) // then start the parsinghttps://stackoverflow.com/questions/54252147
复制相似问题