I am trying to add the product details along with the product Image to the MySql database using NodeJs/Express and postman, but I am getting the issue of filename undefined when i try to make a request to post the product.
I am getting the images that i uploaded from the postman in my code but i cannot send the request of the product.
const db = require("../Database/database");
const multer = require("multer");
const path = require("path");
// *******HANDLING THE FILES********
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(__dirname, "../assets"));
},
filename: (req, file, cb) => {
const extension = path.extname(file.originalname);
cb(null, `${new Date().toISOString().replace(/:/g, "-")}.${extension}`);
},
});
const upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
return cb(new Error("Only image files are allowed"));
}
cb(null, true);
},
limits: {
fileSize: 1024 * 1024 * 5, // 5MB file size limit
},
}).single("prodImage");
Here as well.
// ***********ADD A PRODUCT**********
const addProduct = async (req, res) => {
try {
// Validate that all required fields are provided
const { prodName, prodAddress, prodDescription, prodPrice } = req.body;
if (!prodName || !prodAddress || !prodDescription || !prodPrice) {
return res
.status(400)
.json({ message: "Please provide all product details" });
}
// Access uploaded file information from req.file
const prodImage = path.join("../assets", req.file.filename);
console.log(prodImage);
// Proceed with the database query using prodImage
const [result] = await db.query(
"INSERT INTO product(prodName, prodImage, prodAddress, prodDescription, prodPrice) VALUES (?, ?, ?, ?, ?)",
[prodName, prodImage, prodAddress, prodDescription, prodPrice]
);
res.status(200).json({ message: "A product has been added successfully" });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Internal server error" });
}
};
My GitHub repo : KiitEats/backend at master · Iyabivuz-e/KiitEats · GitHub