Hello, i have problem about files, for exact, my backend can’t read uploaded files, which is from front input type.
const filesRef = useRef(null);
<form
onSubmit={handleSubmit}
method="POST"
encType="multipart/form-data"
>
</form>
I have enctype=multipart/form-data
in form instead of axios headers
i have formData and i’m looping over and get uploaded files dynamically.
But if i pass headers content type
multipart/form-data
in axios headers, i can’t log anything on backend side.
const formData = new FormData();
const files = filesRef.current;
for (let i = 0; i < files.files.length; i++) {
formData.append("files", files.files[i]);
}
try {
const resImage = await baseURL
.post("/products/uploadImage", {
formData,
})
.then(res => console.log(res));
// console.log(resImage);
} catch (error) {
console.log(error);
}
};
Then i import multer
and do configs:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "../uploads");
},
filename: (req, file, cb) => {
console.log(file);
cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname)
);
},
});
const upload = multer({ storage });
i have uploadImages route where i pass multer
middleware:
I know that upload.array(“files”) must be the same as formData.append(“files”)
router.post(
"/uploadImage",
[authenticateUser, upload.array("files")],
uploadImage
);
But on backend when i loggin in console req.body
shows formData: {} – empty object and req.files
– undefined
const uploadImage = async (req, res) => {
console.log(req.body); - ** formData: {} empty object**
console.log(req.files); - **undefined**
const result = await cloudinary.uploader.upload(
req.files.images.tempFilePath,
{
use_filename: true,
folder: "E-Commerce",
}
);
fs.unlinkSync(req.files.images.tempFilePath);
res.status(StatusCodes.OK).json({ src: result.secure_url });
};
I can’t get it what i do wrong, pretend everything is ok but i think multer doesn’t work.
Sharashena is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.