I am trying to create a mern app to upload image to mongodb using multer. I didn't succeed to do so. At first i created a react form to take 3 normal input and one file input to take image. I created a route to upload image and input into the mongodb. I am using multer to upload the image. And i am also confused that where the image will be stored in local storage, client or the server side of the project
Below are the codes:
React.js form
const [helmetName, setHelmetName] = useState("")
const [helmetPrice, setHelmetPrice] = useState("")
const [helmetDescription, setHelmetDescription] = useState("")
const [fileName,setFileName]=useState("")
const onImageChange =(e)=>{
setFileName(e.target.files[0])
}
const submitHandler = () => {
const formData=new FormData();
formData.append("name",helmetName);
formData.append("price",helmetPrice);
formData.append("description",helmetDescription);
formData.append("image",fileName);
dispatch(
placeRequest(formData));
};
return (
<>
<Header />
<div className="container d-flex flex-column justify-content-center align-items-center login-center">
{/* {error && <Message variant="alert-danger">{error}</Message>} */}
{/* {loading && <Loading />} */}
<form
className="Login col-md-8 col-lg-4 col-11"
onSubmit={submitHandler} encType="multipart/form-data"
>
<input
type="text"
placeholder="name"
required={true}
value={helmetName}
onChange={(e) => setHelmetName(e.target.value)}
/>
<input
type="number"
placeholder="helmetPrice"
required={true}
value={helmetPrice}
onChange={(e) => setHelmetPrice(e.target.value)}
/>
<input
type="text"
required={true}
placeholder="helmetDescription"
value={helmetDescription}
className="desc"
style={
{height:"200px"}}
onChange={(e) => setHelmetDescription(e.target.value)}
/>
<input
type="file"
placeholder="helmetPrice"
required={true}
filename="image"
onChange={onImageChange}
/>
<button type="submit">Request for exchange</button>
</form>
Redux action i used
import axios from "axios";
import {
HELMET_CREATE_FAIL,
HELMET_CREATE_REQUEST,
HELMET_CREATE_SUCCESS,
HELMET_LIST_MY_FAIL,
HELMET_LIST_MY_REQUEST,
HELMET_LIST_MY_SUCCESS,
} from "../Constants/HelmetConstant";
import { logout } from "./userActions";
// CREATE ORDER
export const placeRequest = (name,price,description,image) => async (dispatch, getState) => {
try {
dispatch({ type: HELMET_CREATE_REQUEST });
const {
userLogin: { userInfo },
} = getState();
const config = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${userInfo.token}`,
},
};
const { data } = await axios.post(`/api/helmets`, {name,price,description,image}, config);
dispatch({ type: HELMET_CREATE_SUCCESS, payload: data });
} catch (error) {
const message =
error.response && error.response.data.message
? error.response.data.message
: error.message;
if (message === "Not authorized, token failed") {
dispatch(logout());
}
dispatch({
type: HELMET_CREATE_FAIL,
payload: message,
});
}
};
// ORDER DETAILS
export const getHelmetRequestDetails = (id) => async (dispatch, getState) => {
try {
dispatch({ type: HELMET_LIST_MY_REQUEST });
const {
userLogin: { userInfo },
} = getState();
const config = {
headers: {
Authorization: `Bearer ${userInfo.token}`,
},
};
const { data } = await axios.get(`/api/helmets/${id}`, config);
dispatch({ type: HELMET_LIST_MY_SUCCESS, payload: data });
} catch (error) {
const message =
error.response && error.response.data.message
? error.response.data.message
: error.message;
if (message === "Not authorized, token failed") {
dispatch(logout());
}
dispatch({
type: HELMET_LIST_MY_FAIL,
payload: message,
});
}
};
// USER requests
export const helmetRequestList = () => async (dispatch, getState) => {
try {
dispatch({ type: HELMET_LIST_MY_REQUEST });
const {
userLogin: { userInfo },
} = getState();
const config = {
headers: {
Authorization: `Bearer ${userInfo.token}`,
},
};
const { data } = await axios.get(`/api/helmets/`, config);
dispatch({ type: HELMET_LIST_MY_SUCCESS, payload: data });
} catch (error) {
const message =
error.response && error.response.data.message
? error.response.data.message
: error.message;
if (message === "Not authorized, token failed") {
dispatch(logout());
}
dispatch({
type: HELMET_LIST_MY_FAIL,
payload: message,
});
}
};
Express route i created
const storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads/');
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
const upload=multer({storage:storage});
helmetRouter.route(
"/").post(upload.single("image"),
asyncHandler(async (req, res) => {
const newHelmet=new Helmet({
name:req.body.name,
image:req.file.originalname,
description:req.body.description,
price:req.body.price
})
newHelmet.save()
.then(helmet=>res.json(helmet))
.catch(err=>res.status(400).json(`failed`))
}));
And route is :-
app.use("/api/helmets", helmetRouter);