'How can i upload image/pdfs in a MERN project using fetch and store them in folder?
I am trying to add new input field to to add files/images in the registration of a user and save the image name in the mongodb and also save image in a folder(of my choice). I am not able to do. I an using client folder for the frontend and server folder for the backend.
this is my code for storing file:
var storage = multer.diskStorage({
destination : function(req,res,cb){
cb(null,'public/images')
},
filename : function(req,file,cb){
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({dest: storage})
This is my registraion route :
router.post("/register", async(req,res)=>{
try{
let picture = (req.file) ? req.file.filename : null ;
console.log(req.body);
console.log(picture);
const {name,email,phone,work,password,cpassword} = req.body;
const data = new Registration({name,email,phone,work,password,cpassword,picture})
console.log(data);
let response = await data.save();
res.status(200).json({message:"added successfully"});
}catch(e){
console.log(e)
}})
And this is my front end code:
const postdata= async(e)=>{
e.preventDefault();
let url = 'http://localhost:3000/register'
console.log("===", input.image, "===", input.image.name)
const formdata = new FormData();
formdata.append('myimage',input.image,input.image.name )
formdata.append('name',input.name)
formdata.append('email',input.email)
formdata.append('phone',input.phone)
formdata.append('work',input.work)
formdata.append('password',input.password)
formdata.append('cpassword',input.cpassword)
const response = await axios({
method: 'post',
url: url,
body: formdata,
headers: {
'Content-Type': "multipart/form-data",
},
});
if(response.status === 200){
window.alert("added");
setTimeout(()=>{
history("/login")
},1500)
}
else{
window.alert("something went wrong..!");
}
i have added image property in schema with type: string Now, here the problem is when submit clicked formdata is not passing. console.log(req.body) shows-> {} and console.log(picture) shows-> null
any help?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
