【问题标题】:How to upload multiple images to Cloudinary?如何将多张图片上传到 Cloudinary?
【发布时间】:2020-09-20 09:16:42
【问题描述】:

我已经实现了一个工作发布路由,它在提交时将单个图像上传到 cloudinary。

需要进行哪些更改才能启用多张图片上传?任何帮助表示赞赏。

我的发帖路线:

app.post("/portfolio/new", upload.single('image'), function(req, res) {
    cloudinary.v2.uploader.upload(req.file.path, function(err, result) {
        if (err) {
            console.log(err);
        }

        req.body.image = result.secure_url;
        console.log(req.body.image);

        Portfolio.create(req.body.project, function(err, newProject) {]
            if (err) {
                console.log(err);
            }
            res.redirect("/portfolio");
        });
    });
});

我的 HTML(带有 EJS):

<form action="/portfolio/new" enctype="multipart/form-data" method="POST">
    <div>
        Select images: 
        <input type="file" id="image" name="image" accept="image/*" required>
    </div>
</form>

【问题讨论】:

  • @turivishal 感谢您提供文章链接,但我没有足够的经验来重构本指南中的代码以满足我的需要。作者描述了如何将其作为独立的节点应用程序而不是熟悉的 html 表单发布路由来完成。我试着去做,但犯了很多错误,没有进展。
  • 嘿@Ian,您可以从基础开始,观看视频教程并参考堆栈溢出问题并制作演示,请将您的另一个问题作为堆栈溢出中的新问题发布,因为您将从许多堆栈中获得更多答案溢出贡献者..

标签: node.js express multer cloudinary


【解决方案1】:
    const cloudinaryImageUploadMethod = async file => {
      return new Promise(resolve => {
          cloudinary.uploader.upload( file , (err, res) => {
            if (err) return res.status(500).send("upload image error")
              resolve({
                res: res.secure_url
              }) 
            }
          ) 
      })
    }
    
    router.post("/", upload.array("img", 3 ), async (req, res) => {

        const urls = [];
        const files = req.files;
        for (const file of files) {
          const { path } = file;
          const newPath = await cloudinaryImageUploadMethod(path);
          urls.push(newPath);
        }
        
        const product = new Product({ 
          name: req.body.name,
          productImages: urls.map( url => url.res ),
        });

     }

【讨论】:

    【解决方案2】:

    要补充以上内容,你可以用这支笔来做一个简单的javascript多图上传器:codepen.io/team/Cloudinary/pen/QgpyOK

    这是一个非常精美的上传器小部件,内置大量选项:codepen.io/dzeitman/pen/EwgjJV

    希望这有助于其他人尝试做类似的事情,只是想看到一些工作。

    【讨论】:

      【解决方案3】:

      在输入标签中,你应该写...多个。 在发布路线中,应该写

      upload.array("image") 
      

      而不是

      upload.single()
      

      在架构文件中,您应该将图像定义为对象数组

      i.e. image:[
      {
      URL: String,
      filename: String
      }
      ]
      

      【讨论】:

        猜你喜欢
        • 2019-07-13
        • 2018-08-01
        • 2021-01-03
        • 2020-06-24
        • 2020-07-05
        • 2021-07-02
        • 2013-10-07
        • 2022-12-16
        • 1970-01-01
        相关资源
        最近更新 更多