1

I am trying to send uploaded images from client to server. I am doing it in this way:

...
var files = document.getElementById('myForm').files;
var formData = new FormData();
formData.append('image', files[0]);
$.ajax({
    url: '/upload',
    data: formData,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data){
        alert(JSON.stringify(data));
    }
});
...

In server i am using Express. Then, to access uploaded files on server i use connect-busboy module:

...
router.post('/upload', function(req, res, next) {
  req.pipe(req.busboy);
  req.busboy.on('file', function (fieldname, file, filename) {
    //do something
  });
  req.busboy.on('filesLimit', function(){
    //do something
  });
});
...

And to set file size limit of uploaded files i set a fileSize option to 3 mb in a connect-busboy constructor:

...
app.use(
    busboy({
      limits: {
        fileSize: 3*1024 //3 mb
      }
    })
);
...

The problem is that when i am uploading images of size bigger than 3 mb, filesLimit event doesnt fire. Even worse, file event fires in this moment and (!) just 3 mb of file becomes available.

What is wrong? Why filesLimit event doesnt fire? Thanks for your help!

Emil
  • 671
  • 1
  • 6
  • 22

1 Answers1

5

Answering my own question.

I am attaching a file size limit event listener in a wrong way. It turns out that we should attach event on a file object which is a stream in this way.

req.busboy.on('file', function (fieldname, file, filename) {
    file.on('limit', callback); // <- here is
});
Emil
  • 671
  • 1
  • 6
  • 22