I have the Node/Express server with multer for file upload. Form contains 3 fields and they are Title, Description and the Image.
From postman in the body I select form-data and then passing the title, description and then the image.
My route
app.post("/uploads", (req, res, next) => {
upload.single("photo")(req, res, (err) => {
const { title, description } = req.body;
if (!title || !description) {
return res
.status(400)
.json({ error: "Title and description are required" });
}
if (err) {
return res.status(400).json({ error: err.message });
}
if (!req.file) {
console.log(req.file);
return res.status(400).json({ error: "File not uploaded." });
}
res.send(req.file);
});
});
Scenario 1 - When proper inputs (title, description and valid image) are given then image is saved.
Scenario 2 - When valid image but no presence of title or description in the request then simply return the err response saying title/description is needed. But here the err response is sent and at the same time image is also uploaded and I need to prevent it.
Only when all 3 inputs are valid then save the image otherwise no need to save it.
Multer seems to save the image first before the title/description validation happens.
I also tried with another approach by adding a middleware to validate the title/description but its also not working. Because I get undefined as its the form data.
const validateFields = (req, res, next) => {
const { title, description } = req.body;
console.log(title + " " + description); //its undefined
if (!title || !description) {
return res.status(400).send("title and description are neededdd");
}
next();
};
app.post( "/uploads", validateFields, upload.single("photo"), async (req, res) => {
const { title, description } = req.body;
console.log(req.file);
res.send("uploaded");
}
);
Multer config
import multer from "multer";
import { v4 as uuidv4 } from "uuid";
import path from "path";
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(null, uuidv4() + "-" + Date.now() + path.extname(file.originalname));
},
});
const fileFilter = (req, file, cb) => {
const allowedFileTypes = ["image/jpeg", "image/jpg", "image/png"];
if (allowedFileTypes.includes(file.mimetype)) {
cb(null, true); // Accept the file
} else {
cb(
new Error("Invalid file type, only JPEG, JPG, and PNG is allowed!"),
false
);
}
};
const upload = multer({
storage,
fileFilter,
limits: { fileSize: 10 * 1024 * 1024 },
}); //1MB limit
export default upload;
How to handle this - is this possible or do I need to use some other alternative way to fix this.