I try to upload multiple files using multer. here is the frontend code:
const onFileUpload = () => {
// Create an object of formData
const formData = new FormData();
// Update the formData object
formData.append(
"myFiles",
selectedFiles,
);
// Details of the uploaded file
console.log(selectedFiles);
// Request made to the backend api
// Send formData object
axios.post("api/uploadfile", formData);
}
here is the backend code:
const storage = multer.diskStorage({});
const uploadFile = async (req, res) => {
console.log("uploadFile: ",req.files)
return res.status(200).send("alive");
};
router.post(
'/uploadfile',
multer({storage}).array('myFiles'),
uploadFile,
);
the problame is when i consol.log req.files
i resive empty array but i should recive the files array.
what i'm doing wrong
You are using this with the wrong way.
Change it to:
const onFileUpload = () => {
// Create an object of formData
const formData = new FormData();
for (const key of Object.keys(selectedFiles)) {
formData.append("myFiles", selectedFiles[key])
}
// Details of the uploaded file
console.log(selectedFiles);
// Request made to the backend api
// Send formData object
axios.post("api/uploadfile", formData);
}