gpt4 book ai didi

node.js - 穆特错误处理

转载 作者:太空宇宙 更新时间:2023-11-04 00:21:01 25 4
gpt4 key购买 nike

根据 Multer 的官方文档,这是在 Multer 中处理错误的正确方法。

var upload = multer().single('avatar')

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

// Everything went fine
})
})

我的代码设置有点不同,我无法弄清楚如何更改下面的代码以这种方式处理错误。我最大的问题是我的 var 上传设置非常不同,以便与 Amazon S3 配合使用。我如何更改下面的代码以合并如上所示的错误处理?

var upload = multer({
limits : { files: 3 },
storage: multerS3({
s3: s3,
bucket: 'mybucket',
key: function (req, file, cb) {
var fileExtension = file.originalname.split(".")[1];
var path = "uploads/" + req.user._id + Date.now() + "." + fileExtension;
cb(null, path);
},
destination: function(req, file, callback) {
callback(null, './public/uploads');
},
filename: function(req, file, callback) {
callback(null, Date.now() + file.originalname);
}
})

});

我的帖子路由是这样设置的...(仅显示部分代码)

router.post("/", upload.array('image', 3), function(req, res, next){


var filepath = undefined;

var filepath2 = undefined;

var filepath3 = undefined;

if(req.files[0]) {
filepath = req.files[0].key;
}

if(req.files[1]) {
filepath2 = req.files[1].key;
}

if(req.files[2]) {
filepath3 = req.files[2].key;
}

最佳答案

我不知道您是否仍然有疑问,但对于仍在关注它的任何人,您应该使用闭包的力量从内部调用您的函数。

所以你的代码将是这样的:

var upload = multer({
limits : { files: 3 },
storage: multerS3({
s3: s3,
bucket: 'mybucket',
key: function (req, file, cb) {
var fileExtension = file.originalname.split(".")[1];
var path = "uploads/" + req.user._id + Date.now() + "." + fileExtension;
cb(null, path);
},
destination: function(req, file, callback) {
callback(null, './public/uploads');
},
filename: function(req, file, callback) {
callback(null, Date.now() + file.originalname);
}
})

}).array('image', 3);

router.post("/", function(req, res, next) {

upload(req, res, function (err) {
//deal with the error(s)
if (err) {
// An error occurred when uploading
return
}

// Everything went fine
// put here whatever you want to do with your code
var filepath = undefined;

var filepath2 = undefined;

var filepath3 = undefined;

if(req.files[0]) {
filepath = req.files[0].key;
}

if(req.files[1]) {
filepath2 = req.files[1].key;
}

if(req.files[2]) {
filepath3 = req.files[2].key;
}

});

});

这样你就可以自己处理错误,而不是使用express.js的默认处理程序。希望有帮助! :)

关于node.js - 穆特错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44571759/

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