master_alf
master_alf

Reputation: 79

nodejs, connect-busboy. Upload few files

I have trouble with events when upload few files through busboy. My code:

app.post('/multiupload', function(req, res) {
    var fstream;
    var files = [];
    var busboy = new Busboy({headers: req.headers});
    busboy.on('file', function (fieldname, file, filename) {
        fstream = fs.createWriteStream(__dirname + '/../static/uploaded/' + filename);
        file.pipe(fstream);
        fstream.on('close', function(){
            console.log('file ' + filename + ' uploaded');
            files.push(filename);
        });
    });

    busboy.on('end', function(){console.log('END')});

    busboy.on('finish', function(){
        console.log('finish, files uploaded ', files);
        res.redirect('back');
    });
    req.pipe(busboy);
});

My form (Jade template)

form(method="POST", action="/multiupload" name="multiupload_form", enctype="multipart/form-data")
input(type='file' name='multifile', multiple)
input(type="submit" value="Upload!")

Event 'end' just ignored, finish fire in middle of files uploading. Where i wrong?

Server console report:

file 111.gz uploaded
file 222.mp4 uploaded
file 333.jpg uploaded
finish, files uploaded  [ '111.gz', '222.mp4', '333.jpg' ]
file 444 uploaded
file 555.jpg uploaded

Upvotes: 2

Views: 5088

Answers (2)

TheMysterious
TheMysterious

Reputation: 299

close events are called when the file events are closed. you can keep track of the files count in the file event and can use this counter in the close event to see when all the files are uploaded.

below is something you can try

let counter = 0
busboy.on('file', function (fieldname, file, filename) {
        fstream = fs.createWriteStream(__dirname + '/../static/uploaded/' + filename);
        file.pipe(fstream);
        counter++;
        fstream.on('close', function(){
            counter--;
            console.log('file ' + filename + ' uploaded');
            files.push(filename);
            if(counter == 0){
               res.send({message: "All Files Uploaded", })
            }
        });
 });
    req.pipe(busboy);

Upvotes: 0

mscdex
mscdex

Reputation: 106736

busboy does not emit an end event. The finish event is emitted once the entire request has been processed and all file streams have been completely read. So the problem is that the closing of the underlying file descriptor happens in the next tick (or so) which happens after finish is emitted.

If you need to know when all of the file descriptors are closed, then you will need to come up with a way of tracking how many close events have emitted.

Upvotes: 2

Related Questions