快速文件上传。处理 Formidable Parse 中的错误(服务器端)

Express File Upload. Handle Errors inside Formidable Parse (Server Side)

我对 Npm 中的强大模块有疑问。我用它来解析来自我的 Fileupload 前端的传入文件,然后使用 fs.rename 将其保存在本地。这已经有效,到目前为止一切顺利。如果重命名失败,我现在想引入一种错误处理形式,但由于某种原因它告诉我我有一个未处理的错误(即使它已被处理)。

app.post('/upload/:id', function(req, res) {

var type = req.query.type;
console.log(type);
var clubId = req.params.id;
var fileName = clubId.toString();
console.log(clubId);


var form = new formidable.IncomingForm();
form.uploadDir = baseUrl + "indesign_test/sticker_pdfs/" + clubId;
form.on('file', function(field, file) {
    var originalName = file.name;
    if (originalName.indexOf('.pdf') >= 0 && type == '.pdf') {
        fs.rename(file.path, path.join(form.uploadDir, fileName + '.pdf', function(err) {
          if (err) console.log('Test Error: ' + err.code);  // <- Error Handling here
      });
    } else {
        console.log('Error Wrong Format, expected upload in Format of' + type);
    }

});
form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
});
form.on('end', function() {
    res.end('success');
});

form.parse(req);
})

相反,我得到了这个未处理的错误:

 events.js:182
  throw er; // Unhandled 'error' event
  ^

Error: ENOENT: no such file or directory, open '/Users/stickerstars-it-mbp/Desktop/indesign_test/sticker_pdfs/339/upload_be8ff3bd80f5cb2bf1658493157e459f'
stickertmbpsMBP:node-fileupload stickerstars-it-mbp$ 

出于某种原因,您无法在 form.uploadDir 对象上保存上传路径。请改用常规变量。这是更新后的代码示例:

var form = new formidable.IncomingForm();
//upload path on variable instead the form object
var uploadPath = baseUrl + "indesign_test/sticker_pdfs/" + clubId;

form.on('file', function(field, file) {
    var originalName = file.name;
    if (originalName.indexOf('.pdf') >= 0 && type == '.pdf') {
        fs.rename(file.path, path.join(uploadPath, fileName + '.pdf', function(err) {
          if (err) console.log('Test Error: ' + err.code);  
      });
    } else {
        console.log('Error Wrong Format, expected upload in Format of' + type);
    }

});

在此示例中,错误处理没有问题