aquaman aquaman - 2 months ago 5
Node.js Question

Post file and data in same request to node server

I have a form in HTML with two inputs - 1 text and 1 file.

<form method="post" action="http://localhost:3000/users">
<input type="text" name="username" />
<input type="file" name="file" />
<button type="submit">Submit</button>
</form>


Now I am posting it to a node server-

router.post('/users', function(req, res, next){
req.pipe(req.busboy);
req.busboy.on('file', function(fieldname, file, filename){
var fstream=fs.createWriteStream('./uploads/'+filename);
file.pipe(fstream);
fstream.on('close', function(){
var user = User({
username: req.body.username,
});
user.save(function(err){
if(err)
res.json({error: err});
else
res.redirect('/');
});
});
});
});


But I am only able to get either username or file (when I use
enctype="multipart/form-data"
in HTML form.) at a time.

Is there any way to save both in a single request. If yes then how ?

Any help is appreciated.

Thanks.

Answer

You're only listening for file fields. If you want to be notified about non-file fields, then you need to also add a 'field' event listener:

req.busboy.on('field', function(key, val, keyTrunc, valTrunc) {
  console.log(key, val);
});
Comments