如何在 mern 中上传多张 cloudinary 图像?

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

这是产品控制器,我在其中添加产品并使用 for 循环一张一张地上传多张图片。


//Create product -- Admin
exports.createProduct = catchAsync( async (req, res, next) => {

  let images = [];

  if(typeof req.body.images === 'string') {
    images.push(req.body.images)
  }
  else {
  images = req.body.images
}
  const imageLinks = [];
  
  for (let i = 0; i < images.length; i++) {
    const { path } = "image/";  
    const result = await cloudinary.v2.uploader.upload(images[i].path, {
      folder: 'products',
    });
    imageLinks.push({
      public_id: result.public_id,
      url: result.secure_url,
    });
  }
  req.body.images = imageLinks;

  req.body.user = req.user.id;

  const product = await Product.create(req.body);

  res.status(201).json({ success: true, product  });

});

在上面,我从 req.body.images 接收图像,然后将多个图像推送到 cloudinary,并在 imageLink 中,但是当我上传一个图像时它正在工作,但在多个图像的情况下不是。

    const submitHandler = (e) => {
        e.preventDefault()
        let myForm = new FormData();

        myForm.set('name' , name);
        myForm.set('price' , price);
        myForm.set('description' , description);
        myForm.set('category' , category);
        myForm.set('stock' , stock);

        images.forEach((image) => {
            myForm.append('images' , image);
        })
    dispatch(newProductAction(myForm))
    }
    `This is submit handler where i am sending all data through frontend . and newProductAction is funtion created in redux
`
mern cloudinary
2个回答
0
投票

此链接上的文章(使用 Node.js、Cloudinary 和 Multer,但由于 Express.js 是一个 Node.js 框架,您可以解决他们提供的解决方案并使用 Express.js 制作相同的解决方案),(https ://andela.com/insights/how-to-use-cloudinary-and-nodejs-to-upload-multiple-images/)


-3
投票
© www.soinside.com 2019 - 2024. All rights reserved.