Search code examples
node.jsexpressnpmbusboy

Express Busboy on File Event not firing


I am trying to make busboy work with my express code, but none of its events are firing,

there are no silly mistakes like non-matching input field names etc.

Here is

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');    
var index = require('./index');
var liveupload = require('./liveupload');

var app = express();

// view engine setup    
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/bower_components/dropzone/dist'));

app.use('/', index);
app.use('/liveupload', liveupload);


app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found SIR');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

This is desired action : liveupload

var express = require('express');
var router = express.Router();

var Busboy = require('busboy');

router.post('/', process_upload);

function process_upload(req, res, next){



var busboy = new Busboy({ headers: req.headers });

// Listen for event when Busboy finds a file to stream.
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
console.log("In bus boy");
        // We are streaming! Handle chunks
        file.on('data', function (data) {
                // Here we can act on the data chunks streamed.
                console.log("Chunk mila");
        });

        // Completed streaming the file.
        file.on('end', function () {
                console.log('Finished with ' + fieldname);
        });
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
      console.log('Field [' + fieldname + ']: value: ' + inspect(val));
    });

console.log("out of busboy");
res.sendStatus(200);

}


module.exports = router;

And here is the UI which uploads the file.

<script language="JavaScript" type="text/javascript" src="javascripts/jquery.min.js"></script>
<script>
$(function(){
  Dropzone.options.himanshu = {
   paramName: "file",
         maxFilesize: 5,
    addRemoveLinks: true,
    dictResponseError: 'Server not Configured',
    acceptedFiles: "*.*",
    init:function(){
      var self = this;
      // config
      self.options.addRemoveLinks = true;
      self.options.dictRemoveFile = "Delete";
      //New file added
      self.on("addedfile", function (file) {
        console.log('new file added ', file);
      });
      // Send file starts
      self.on("sending", function (file) {
        console.log('upload started', file);
        $('.meter').show();
      });

      // File upload Progress
      self.on("totaluploadprogress", function (progress) {
        console.log("progress ", progress);
        $('.roller').width(progress + '%');
      });

      self.on("queuecomplete", function (progress) {
        $('.meter').delay(999).slideUp(999);
      });

      // On removing file
      self.on("removedfile", function (file) {
        console.log(file);
      });
    }
  };
})  
</script>




<link href="stylesheets/dropzone.css" rel="stylesheet"/>
<form action="/liveupload" method="post" class="dropzone" id="himanshu" enctype="multipart/form-data" >
 <div class="fallback">
    <input name="file" type="file" multiple />
  </div>

</form>

I have tried numerous ways, but still cant figure out why busboy is not working.

any help will be greatly appreciated


Solution

  • Problem was with liveupload.js

    here is corrected code -

    var busboy = new Busboy({ headers: req.headers });
    
    
    
       // Listen for event when Busboy finds a file to stream.
        busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
            console.log("In bus boy");
            // We are streaming! Handle chunks
            file.on('data', function(data) {
                // Here we can act on the data chunks streamed.
                console.log("Chunk mila");
            });
    
            // Completed streaming the file.
            file.on('end', function() {
                console.log('Finished with ' + fieldname);
            });
        });
        busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
            console.log('Field [' + fieldname + ']: value: ' + inspect(val));
        });
    
        busboy.on('finish', function() {
            console.log("out of busboy");
            res.sendStatus(200);
        });
        req.pipe(busboy);
    }