这是产品控制器,我在其中添加产品并使用 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
`
此链接上的文章(使用 Node.js、Cloudinary 和 Multer,但由于 Express.js 是一个 Node.js 框架,您可以解决他们提供的解决方案并使用 Express.js 制作相同的解决方案),(https ://andela.com/insights/how-to-use-cloudinary-and-nodejs-to-upload-multiple-images/)