I read all the questions related to this already and nothing works. I spent the entire day on this and I can't figure out what's wrong.
I am trying to upload a file to my database using React, mongoose, mongoDB and express/node.
Here is what I already did:
- Added method="post" and enctype="multipart/form-data" to my form
- the "name" property of the file input is "icon" and in the middleware upload.single("icon") too.
On submit I have a function action that is called.
export const updateUserIconette = icon => async dispatch => {
console.log("Number 1");
console.log(icon);
try {
const res = await axios.post("/me", icon);
dispatch({
type: UPDATE_PROFILE_SUCCESS,
payload: res.data
});
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach(error => dispatch(setAlert(error.msg, "danger")));
}
dispatch({
type: UPDATE_PROFILE_ERROR
});
}
};
Here, the console.log number 1 logs and the log of icon too, which is a file object.
And the API Post route is here:
const multer = require("multer");
const storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, "./uploads/");
},
filename: function(req, file, callback) {
callback(null, file.originalname);
}
});
const fileFilter = (req, file, callback) => {
if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
callback(null, true);
} else {
callback(null, false);
}
};
const upload = multer({ storage: storage, fileFilter: fileFilter });
router.post(
"/",
[
auth,
upload.single("icon")
],
async (req, res) => {
console.log("number 2")
console.log(req.file)
// Build the Profile object
const profileFields = {};
profileFields.user = req.user.id;
if (req.body.username) profileFields.username = req.body.username;
if (req.body.bio) profileFields.bio = req.body.bio;
if (req.body.location) profileFields.location = req.body.location;
if (req.file) profileFields.icon = req.file.path;
try {
let user = await User.findOne({ _id: req.user.id });
if (user) {
//Update
user = await User.findOneAndUpdate(
{ _id: req.user.id },
{ $set: profileFields },
{ new: true }
);
return res.json(user);
}
await user.save();
res.json(user);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
}
);
Here, the console.log number 2 logs but not the req.file because it is empty.