aquaman aquaman - 1 year ago 42
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>

Now I am posting it to a node server-'/users', function(req, res, next){
req.busboy.on('file', function(fieldname, file, filename){
var fstream=fs.createWriteStream('./uploads/'+filename);
fstream.on('close', function(){
var user = User({
username: req.body.username,
res.json({error: err});

But I am only able to get either username or file (when I use
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.


Answer Source

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);