node.js - Node/Express/MongoDB 应用程序:使用 Multer 和 Cloudinary 上传多个图像
问题描述
希望有人可以帮助我:
我正在开发一个 Node/Express/Mongo CRUD 应用程序,其中每个帖子/文档都有一个图像。我正在使用 multer 和 cloudinary 来上传图像。但是,我希望用户能够将多张图片上传到每个帖子。理想情况下,图像 url/路径和 ID 将存储在我的数据库中的数组中。
我已经尝试和研究了几个小时,但似乎无法使其工作,并且没有教程解释如何使用 multer 和 cloudinary 来完成这个(简单的)任务。
这是我用来为每个帖子上传一张图片的代码,它正在工作:
// CREATE Route - add new post to DB
router.post("/", middleware.isLoggedIn, upload.single('image'), function(req, res) {
cloudinary.v2.uploader.upload(req.file.path, function(err, result) {
if(err) {
req.flash('error', err.message);
return res.redirect('back');
};
// add cloudinary url for the image to the post object under image property
req.body.post.image = result.secure_url;
// add image's public_id to post object
req.body.post.imageId = result.public_id;
// add author to post
req.body.post.author = {
id: req.user._id,
username: req.user.username
}
Post.create(req.body.post, function(err, post) {
if (err) {
req.flash('error', err.message);
return res.redirect('back');
}
res.redirect('/posts/' + post.id);
});
});
});
为了实现这个目标,我需要如何更改此代码?在此先感谢您的帮助!
解决方案
上传 API 目前只支持一次上传单个文件,它确实有很高的并发率(大约 40-50 个并发调用),因此您可以使用多线程一次上传多个文件。您还可以使用异步调用,并通过添加async
参数并将其设置为true
.