I'm creating a react app for found objects and I want to allow users to upload photos of these objects
I tried to send the image through a post request with axios to a mongoose server but it doesn't work.
So this is how I store the image in the react component with a preview :
handleImage(event) {
let reader = new FileReader();
let file = event.target.files[0];
reader.onloadend = () => {
this.setState({
image: file,
imagePreviewUrl: reader.result
});
}
and this is how I send it :
reader.readAsDataURL(file)
axios.post("/api/putData", {
id: idToBeAdded,
author : "TODO", //TODO
title: infos.title,
type: infos.type,
reward: this.state.reward,
description: infos.description,
image: infos.image,
});
Here is my code to handle the request on the other side :
router.post("/putData", (req, res) => {
let data = new Data();
const { id, author, title, type, reward, description, image } = req.body;
/*if ((!id && id !== 0) || !message) {
return res.json({
success: false,
error: "INVALID INPUTS"
});
}*/
data.title = title;
data.type = type;
data.reward = reward;
data.description = description;
data.author = author;
data.id = id;
data.image.data = image;
data.image.contentType = 'image/png'
data.save(err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
So this image is part of a form and when I submit it without the image I have a new document in the DB without any image (which is okay) but when I try to load one no document is created.
What can I do ?