Prayag C. Patel
Prayag C. Patel

Reputation: 143

busboy not firing field, file event

In below code, only finish event called.


var Busboy = require('connect-busboy');

app.use(Busboy());

app.post('/fileupload', function(req, res) {
  var fstream;

  req.pipe(req.busboy);

  req.busboy.on('error', function(err){
    console.log(err);
  });

  req.busboy.on('field', function(fieldname, val, valTruncated, keyTruncated) {
    console.log("fieldname: " + fieldname); 
  });

  req.busboy.on('file', function (fieldname, file, filename) {
    console.log("filename: " + filename); 
    fstream = fs.createWriteStream(__dirname + '/files/' + filename);
    file.pipe(fstream);
    fstream.on('close', function () {
      res.redirect('back');
      console.log("fileupload end");
    });
  });

  req.busboy.on('finish', function() {
    console.log('Done parsing form!');
  });
});

Upvotes: 5

Views: 4699

Answers (2)

BruceJo
BruceJo

Reputation: 781

OK, late to the party. But I had this issue and only found the solution via with the help of ChatGPT.

I wanted to keep with busboy specifically so I could stream the file and the only way to stream is it via the file event.

My problem

I used a javascript upload using FormData Request & Fetch. Plus my data was not an HTML input='files'. I was creating the data from my application and saving it to a file.

None of this was a problem when I just set the request body to simply be the data. It became a problem when I started using multpart/form-data.

Solution

To enable the busboy file event you need to make sure the data has a filename associated with it. That means you need to call the .append method with a filename argument.

  const formData = new FormData();
  const fileName = 'myFileName.ext';
  formData.append('files', blobData, fileName);

Once I set the filename then my busboy file event fired properly, Yay!

Other note:

If you append a filename then append expects blobData.

Upvotes: 0

mscdex
mscdex

Reputation: 106736

The reason why you're not seeing any data is because you're already using the multer module which also parses multipart/form-data requests, saving files to disk. If you're not using multer and want to use busboy manually as you show in your code, you will need to remove the app.use(multer()); line.

Upvotes: 4

Related Questions