我正在尝试使用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 ...);
答案 0 :(得分:3)
这是因为你正在尝试使用旧的multer api。在当前版本中,没有事件处理程序:onFileUploadComplete
和onParseStart
。请查看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
})
})