我正在尝试使用 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。在当前版本中,没有事件处理程序: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
})
})
关于node.js - Nodejs multer 选项不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33209991/