我正在使用 Express 4 和 Formidable 处理文件上传表单,但遇到了一些问题。
我想要实现的是:
-Check if file is selected and extension/format before file is uploaded to the server and abort if not .txt
-Write file "info" to db, copy file from tmp folder to dest. folder and delete tmp file.
我的代码:
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname, '/uploads/tmp');
form.keepExtensions = true;
form.on('error', function(err) {
console.log(err.message);
req.flash('error', err.message);
res.redirect('/upload');
});
form.on('file', function(name, file){
var modname = file.path.split('/')[file.path.split('/').length-1]
var finals = path.join(__dirname, 'uploads/finals/' + modname);
fs.rename(file.path, finals, function(err){
if(err) throw err;
});
new Input({
user: req.user,
name: file.name,
size: file.size,
path: finals,
type: file.type
}).save(function(err, upload, count){
if (err){
console.log(err);
}
});
});
form.on('end', function (){
req.flash('info', 'Input file uploaded');
res.redirect('/upload');
});
form.parse(req);
});
我不确定在哪里检查“如果文件被选中”和格式以及如何检查?我可以检查大小是否 === 0 然后发出错误事件吗?如果如何执行此操作或是否有任何其他方法可以检查在
form.parse
执行之前是否选择了文件?这是在正确的事件中移动文件的正确方法吗?但是,如果“写入数据库”或“移动文件”失败,我该如何中止?这可以用异步完成吗?