gpt4 book ai didi

node.js - Nodejs multer 选项不会触发

转载 作者:太空宇宙 更新时间:2023-11-03 22:53:20 25 4
gpt4 key购买 nike

我正在尝试使用 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
})
})

关于node.js - Nodejs multer 选项不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33209991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com