Node / Express / MongoDB应用程序:使用Multer和Cloudinary上传多个图像

问题描述 投票:0回答:1

希望有人可以帮助我:

我正在开发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);
      });
    });
});

为了实现这一目标,我需要如何更改此代码?在此先感谢您的帮助!

node.js mongodb express multer cloudinary
1个回答
0
投票

上传API目前一次只支持单个文件上传,它具有高并发率(大约40-50个并发调用),因此您可以使用多线程一次上传多个文件。您还可以使用异步调用,并通过添加async参数并将其设置为true告诉Cloudinary在后台执行上载。

© www.soinside.com 2019 - 2024. All rights reserved.