My issue is that when I make the request in thunder client extension in vs code, it works, but in my code I tried but didn’t succeed, Image files seem to not upload.
I have tried multiple ways to resolve this issue but without success, using chat gpt didn’t help at all. Please consider helping.
product create route:
“/products”
.post(auth, fileUpload(fileValidation.image).array('images', 5), catcher(controller.createProduct))
multer file for file validation:
import multer from "multer";
export const fileValidation = {
image: ['image/png', 'image/jpeg', 'image/jpg', 'image/webp'],
pdf: ['application/pdf']
}
function fileUpload(customValidation = []) {
const storage = multer.diskStorage({})
const fileFilter = ((req, file, cb) => {
if (customValidation.includes(file.mimetype)) {
cb(null, true);
} else {
cb("Invalid file format", false)
}
})
return multer({ fileFilter, storage });
}
export default fileUpload;
Product create controller:
export const createProduct = async (req, res, next) => {
const { name, price, salePrice, tax, description, category, stock, quantity, status } = req.body;
const { files } = req;
if (!name || !price || !description || !category || !stock || !quantity || !status || !files) {
return next(
new ResponseError(
"Please provide correct data for the product",
statusCodes.BAD_REQUEST
)
);
}
let images = [];
const uploadPromises = files.map(async file => {
const { path } = file;
const { secure_url, public_id } = await cloudinary.uploader.upload(path, {
folder: process.env.CLOUDINARY_PRODUCTS_FOLDER
});
images.push({ url: secure_url, public_id });
});
await Promise.all(uploadPromises);
// Create a new object with only the required fields
const productData = {
name,
price,
description,
category,
stock,
quantity,
status,
seller: req.user._id,
images,
};
// Add optional fields if they are present in the request body
if (tax) {
productData.tax = tax;
}
if (salePrice) {
productData.salePrice = salePrice;
}
const product = await Product.create(productData);
res.status(statusCodes.OK).json({
message: "Product successfully created",
product
});
};
Image dropzone code:
const [coverImages, setCoverImages] = useState([]);
const [files, setFiles] = useState([]);
const onDrop = useCallback(
(acceptedFiles) => {
const remainingSlots = 5 - coverImages.length;
const filesToAdd = acceptedFiles.slice(0, remainingSlots);
setFiles(files.concat(filesToAdd));
updateProductData("images", [...files, ...filesToAdd]);
filesToAdd.forEach((file) => {
const reader = new FileReader();
reader.onload = () => {
setCoverImages((prevImages) => [...prevImages, reader.result]);
};
reader.readAsDataURL(file);
});
},
[coverImages]
);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
multiple: true,
onDrop: onDrop,
});
//--------------------------------------------------
<MUI.Box
{...getRootProps()}
className="absolute w-full flex-col h-full flex items-center justify-center cursor-pointer gap-3"
>
<img
src="/src/assets/draganddropareacloudimage-removebg-preview.png"
width={150}
height={100}
className=""
alt=""
/>
<MUI.Typography
variant="subtitle1"
className="dark:text-white text-center"
>
drag and drop files or{" "}
<span className="underline text-blue-500">click</span> to browse
files
</MUI.Typography>
</MUI.Box>
<input
{...getInputProps()}
type="file"
multiple
onChange={(e) => onDrop(e.target.files)}
className="hidden"
/>
</MUI.Box>
BTW using Material UI*
Product data object:
const [productData, setProductData] = useState({
name: "",
price: "",
description: "",
category: "",
stock: 0,
quantity: 0,
salePrice: 0,
tax: 0,
status: "Pending",
images: [],
});
Update products function
const updateProductData = (field, value) => {
setProductData({ ...productData, [field]: value });
};
form handle submit:
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
for (const key in productData) {
if (key === "images") {
for (let i = 0; i < productData.images.length; i++) {
formData.append("images", productData.images[i]);
}
continue;
}
formData.append(key, productData[key]);
}
const formKeys = Array.from(formData.keys());
console.log(formKeys);
const formDataValues = Array.from(formData.values());
console.log(formDataValues);
createProduct(formData);
};
const createProduct = async (data) => {
// setLoadingToCreateProduct(true);
console.log(data);
try {
const res = await axios.post("/products", data);
if (res) {
console.log(res.data);
}
} catch (error) {
console.log(error);
} finally {
// setLoadingToCreateProduct(false);
}
};
When Ienter code here run the code in thunder client it works, but here it isn’t

