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

时间:2017-09-05 16:05:11

标签: node.js express formidable

我对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$ 

1 个答案:

答案 0 :(得分:1)

由于某种原因,您无法在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);
    }

});

在此示例中,错误处理可以正常运行