I want to upload images with Multer and when I test it with postmanden it works fine but when I send a request with axios the req.file is undefined but I get the data I want in req.body and I get error 400 in frontend.
multer.ts
import { Request, Response, NextFunction } from "express";
import multer from "multer";
const storage = multer.diskStorage({
destination: "uploads/",
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(null, uniqueSuffix);
},
});
const uploads = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5,
files: 1,
fieldSize: 1024 * 1024 * 5,
},
fileFilter: (req, file, cb) => {
if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
cb(null, true);
} else {
cb(new Error("File type not supported!"));
}
},
});
interface RequestWithUser extends Request {
user?: {
id: number;
email: string;
};
}
export function uploadImage(
req: RequestWithUser,
res: Response,
next: NextFunction
) {
uploads.single("image")(req, res, (err) => {
if (err instanceof multer.MulterError) {
console.error("MulterError =>", err.message);
return res.status(400).json({ message: err.message });
}
if (err) {
console.error("MulterError =>", err.message);
return res.status(400).json({ message: err.message });
}
if (!req.file) {
console.error("Please upload an image");
return res.status(400).json({ message: "Please upload an image" });
}
console.log("req.body MWW =>", req.body);
console.log("req.file MWW =>", req.file);
next();
});
}
router.post(
"/create-image",
authorize,
uploadImage,
createImageController.createImage
);
Example axios request
const handleGenerateImage = async (prompt: string, image: string) => {
const formData = new FormData();
for (const [key, value] of Object.entries({ prompt, image })) {
formData.append(key, value as string | Blob);
}
console.log("formData", formData);
try {
const result = await axios.post(
"http://localhost:5000/api/create-image",
formData,
{
responseType: "json",
headers: {
Accept: "multipart/form-data",
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${TOKEN}`,
},
}
);
console.log("result", result);
return result;
} catch (error) {
console.log("error", error);
return;
}
};
Error
LOG error [AxiosError: Request failed with status code 400]**
Form data log
**
LOG formData {“_parts”: [[“prompt”, “Superman”], [“image”, “file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FstickerAI-4f69cda2-177b-4e6a-9b97-2784a47b4c88/ImagePicker/2fcasdf1-30f5-4149-89a1-0304b7b3acfc.jpeg”]]}
I tried taking the data from req.body and assigning it to req.file,
I tried with req.files and tried to use it as an array,
I tried removing content-typpe,
app.use(bodyParser.urlencoded({ extended: false })); tried it as true false,
and etc