1

I have a project in which I am using a basic sign up page for a user to enter their details. I am using express JS at the backend

In this, I am also asking them to upload a picture. But for the picture to be uploaded, I need to make the enctype of the form as multipart/form-data. The image gets uploaded, but the problem is that none of the other data is recorded.

This is the html:

<form action="/create"  method="POST" class="profile" enctype="multipart/form-data">
        <input type="file" name="profile_image" class="img_upload" /><br><br><br>
        <div class="name_age" >
            <input type="text" name="name" class="name" placeholder="Full name">
            <b class="age"> Age </b>
            <input type="date" name="age" class="age"/> 
        </div>
<input type="submit" name="submit" value="Update Profile"  class="button"/>
</form>

And this is expressJS code for handling it:

app.post('/create',(req,res)=>{
    var d = req.body 
    console.log(d)

    upload(req,res,function(err){   //this is a multer function to store the image  
        if(err)
            res.end(err)
        else{       
            res.end('success')
        }
    })
})

The console.log(d) returns an empty object. Without multipart/form-data the image doesn't get uploaded,but the rest of the data gets recorded.

How do I solve this issue?

1 Answer 1

1

I actually tried this as well in my project some months ago and got a similar problem with busboy as well as multer. You can have a onclick event on the button where you can have a setTimeout of 3,4 seconds (the usual time it will take to upload the image and send response) and send the text fields in the body in the ajax request to your url /create. Or just ditch the post request using the <form> tag and just send the image as well as the text fields in the ajax request. Hope it helps

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I thought of something like that too. The way I solved it is by creating 2 forms, 1 for the image and the other for the text fields. Then I made one button and called a function in the JS when the button is clicked which first submits the image form, and then after a slight delay of about 4 seconds, submits the 2nd form
Nice. Or you can just use ajax for both the image and text fields. I have been using React for sometime now and as every request is ajax in React, I am more okay with ajax now. Before using handlebars with Express, I was in a real fix regarding this. Glad I could be of help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.