Reputation: 37
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?
Upvotes: 0
Views: 788
Reputation: 185
I think the problem is in your registration route. You didn't write the "upload.single('')" to tell multer which route will be needing the diskStorage. Try writing your code and like this and let's see.
router.post("/register", upload.single(""),async(req,res)=>{}
In the quotation marks inside the upload.single(), you must enter the name of the input tag you used in the front-end for the image.
Upvotes: 1