Search code examples
javascriptnode.jsexpressmulter

How to get the body before uploading file in multer?


In my project the admins have the ability to upload MP3 files and submit parameters to it like song name.

I decided using multer middleware for handling multipart/form-data.

My problem is req.body.gender returns always undefined, because I have to use it inside the uploadSong listener. I want to upload the song when the gender is zero.

index.ejs

<form method="post" action="/acp" role="publish" enctype="multipart/form-data">
    <div class="form-group">
        <input type="file" name="song" id="song" accept="audio/mpeg">
    </div>

    <input type="checkbox" name="gender" checked data-toggle="toggle" data-on="Male" data-off="Female">
</form>

app.js

var uploadSong = upload.single('song');
app.post('/acp', isLoggedIn, function (req, res) {

    console.log(req.body.gender); // returns "undefined"

    if(req.body.gender == 0) { // returns "undefined"

        uploadSong(req, res, function (err) {
            if (err) {
                res.send('uploaded');
                return;
            }
            res.redirect('/');

        });
    
    }
});

Solution

  • (A) Not possible with multer.

    (B) Use busboy. It uses streams to parse the form data and so you can get form elements values before the file upload and the fields are made available as events.

    (C) Another solution (if you prefer using multer) is to use multer but add a header to send the value of the parameter to check before file upload. Headers are available as soon as the request reaches the server.