I am arslan chaudhry Mern stack develpore. I am an issue for the last 4 days. I am unable to upload images in the MERN stack. I am using Axios in ReactJS for this purpose. I have created a state and then use it post request. Like This:
const [FormInfo, setFormInfo] = useState({productName:"",image:""})
//function for setting state
let names;
const setInputsData = (e) => {
names = e.target.name;
setFormInfo({
...FormInfo,
[names]: e.target.value,
});
};
const submiteDataNow = async (e) => {
e.preventDefault();
const res = await axios.post("/Create_Post", FormInfo);
};
FORM
<form method="post" enctype="multipart/form-data">
<input name="ProductName" onChange={setInputsData}/>
<input type="file" name="images" accept="image/*" onChange={(e) => {
FormInfo.images = e.target.files;}} multiple />
<input onClick={submiteDataNow} type="submit" />
<form />
But I am receiving an empty image object in the backend. Like:
Dear seniors please also share code about how I can upload pics in NodeJS using multer.
CodePudding user response:
I would like to see the backend as well. Are you using multer? You can read this article as it explains the file uploading in MERN using Multer. https://abbasimusab2000.medium.com/mern-stack-uploading-files-with-multer-dd86213f3cef
CodePudding user response:
maybe because you are not setting state using callback setFileInfo instead youre setting it using the variable FileInfo . State should not be modified in this way