Reputation: 149
I've implemented a working post route that uploads a single image to cloudinary on submit.
What needs to be changed to enable multiple image upload? Any help is appreciated.
My post route:
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");
});
});
});
My HTML (with 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>
Upvotes: 3
Views: 11376
Reputation: 1063
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 ),
});
}
//error: the files is not iterable
Upvotes: 4
Reputation: 13
in input tag, you should write ... multiple. and in post route, one should write
upload.array("image")
instead of
upload.single()
and in the schema file, you should define the image as an array of objects
i.e. image:[
{
URL: String,
filename: String
}
]
Upvotes: 0
Reputation: 11
To add to the above, you can use this pen for a simple javascript multiple image uploader: codepen.io/team/Cloudinary/pen/QgpyOK
Here's a very fancy uploader widget with a ton of options built-in: codepen.io/dzeitman/pen/EwgjJV
Hope this helps others trying to do something similar and just want to see something working.
Upvotes: 1