Nodejs multer 选项不会触发

Nodejs multer options don't fire

我正在尝试使用 multer 保存文件,但它并不能正常工作:

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
    cb(null, './')
},
filename: function (req, file, cb) {
    cb(null, file.originalname + '-' + Date.now() + '.' + path.extname(file.originalname));
    }
});

var upload = multer({ storage: storage,
onFileUploadComplete : function (file) {
    console.log('Completed file!');
},
onParseStart : function() {
     console.log('whatevs');
}});

app.post('/upload' ,upload.single('thisisme'), function(req,res) {});  

文件确实已保存,但 ParseStart 或 UploadComplete 从未触发。这是为什么?我也尝试使用 app.use ( multer ... );

这是因为您正在尝试使用旧的 multer api。在当前版本中没有事件处理程序:onFileUploadCompleteonParseStart。请查看文档以获取 api 详细信息:https://github.com/expressjs/multer

这部分代码看起来没问题:

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
    cb(null, './')
},
filename: function (req, file, cb) {
    cb(null, file.originalname + '-' + Date.now() + '.' + path.extname(file.originalname));
    }
});

这也可以:

app.post('/upload' ,upload.single('thisisme'), function(req,res) {});

这是错误的:

var upload = multer({ storage: storage,
onFileUploadComplete : function (file) {
    console.log('Completed file!');
},
onParseStart : function() {
     console.log('whatevs');
}});

改成这样:

var upload = multer({ 
  storage: storage,
  fileFilter:function(req, file, cb) {
    //Set this to a function to control which files should be uploaded and which should be skipped. It is instead of onParseStart.
  }
});

除了onFileUploadComplete,什么都没有。但是:

app.post('/upload' ,upload.single('thisisme'), function(req,res) {
//this is call when upload success or failed
});

你可以把它改成这样:

app.post('/upload', function (req, res) {
  upload.single('thisisme')(req, res, function (err) {
    if (err) {
      // An error occurred when uploading
      return
    }

    // Everything went fine, and this is similar to onFileUploadComplete
  })
})