I want to dynamically change the uploads destination based on a string I get from req.body.slug
, so I am including multer inside the route like so:
const storageMulti = multer.diskStorage({
destination: initialDestination,
filename: function (req, file, cb) {
cb(null, Date.now() + "-" + file.originalname);
},
});
const uploadMulti = multer({ storage: storageMulti });
router.post("/multiupload", (req, res) => {
const categoryFolder = req.body.slug ? req.body.slug : "all";
const updatedStorage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, `./frontend/public/gallery/${categoryFolder}`);
},
filename: function (req, file, cb) {
cb(null, Date.now() + "-" + file.originalname);
},
});
// Use multer middleware with updated destination
const updatedUploadMulti = multer({ storage: updatedStorage });
// Use multer middleware with updated destination
updatedUploadMulti.array("images")(req, res, (err) => {
if (err) {
return res.status(400).send("Error uploading files.");
}
// Access uploaded files via req.files array
console.log(req.files);
res.send("Images uploaded successfully.");
});
});
That works as far as the uploading goes, the issue is that req.body.slug
is undefined unless I change the route definition to include multer, which goes like so but is not acceptable because I want to change the upload folder based on req.body.slug
:
router.post("/multiupload", uploadMulti.array("images"), (req, res) => { // if I do this then I do get req.body.slug but this is not acceptable
I am sending data from an RTK Query Mutation if that makes any difference:
const toUpload = new FormData();
selectedImages.forEach((image) => {
toUpload.append("images", image);
});
toUpload.append("slug", "white-shirt");
await upload(toUpload);
toast.success("Images uploaded successfully");