I am uploading an image and saving it to mongodb but it is showing following error:
message: "postMessage validation failed: selectedFile: Cast
name: "ValidationError"
_message: "postMessage validation failed"
I am using react-base64 on the front end side to upload the image.
<FileBase type="file" multiple={false} onDone={(base64) => setPostData({ ...postData, selectedFile: base64})} />
And i am adding it to DB via fetch :
let handleSubmit = (event) => {
event.preventDefault();
console.log(postData);
fetch(`http://localhost:5000/posts/create`, {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
// 'Accept': 'application/json'
},
body: JSON.stringify(postData),
})
.then(response => response.json())
.then((dataFromServer) => {
console.info(dataFromServer);
})
.catch(error => console.error(error));
}
Can anyone tell me what I am doing wrong and how can i fix this issue
CodePudding user response:
In the FileBase component, you need to do in this way.
You need to destructure the parameter on onDone
. In this way onDone={({base64}) => yourFunction()}
You can use this one.
<FileBase type="file" multiple={false} onDone={({base64}) => setPostData({ ...postData, selectedFile: base64})} />