Hi I try to add images to my server. So I made form in React and back-end post method. But my file.name is undefined and I cant add files to my server. For Image uplod I use react component from here : https://www.npmjs.com/package/react-images-upload
...
function handleSubmit(e) {
e.preventDefault();
const config = {
headers: {
'content-type': 'multipart/form-data',
},
};
console.log(mainPicture);
axios
.post(
prefix + '/api/add_project',
{
params: {
name: name,
description: description,
address: address,
used: used,
about: about,
mainPicture: mainPicture,
},
}
)
.then((response) => {
alert('The file is successfully uploaded');
})
.catch((error) => { alert('failed')});
}
....
<form onSubmit={handleSubmit}>
<label>
Name:
<input
value={name}
onChange={(e) => setName(e.target.value)}
type="text"
defaultValue="Name"
/>
</label>
<ImageUploader
name="mainPicture"
{...props}
buttonText="Choose Main Project Image"
withIcon={true}
withPreview={true}
onChange={setMainPicture}
imgExtension={['.jpg', '.gif', '.png', '.gif']}
maxFileSize={5242880}
singleImage={true}
/>
<button type="submit">Upload</button>
</form>
My Node.js backend
router.post('/api/add_project', (req, res, next) => {
console.log("Request ---", req.body.params);
console.log(JSON.stringify(req.body.params.mainPicture));
if (Object.keys(req.body.params.mainPicture).length == 0) {
return res.status(400).send('No files were uploaded.');
}
console.log(req.file);
var file = req.file;
console.log('file name: ' + file.name);
if (
file.mimetype == 'image/jpeg' ||
file.mimetype == 'image/png' ||
file.mimetype == 'image/gif'
) {
file.mv('public/images/projects/' + file.name, function (err) {
if (err) return res.status(500).send(err);
});
}
});
In my pm2 monit I can see that file is undefined:
Did I made mistake in front-end or in back-end?
How should I solve this problem?