简体   繁体   English

nodejs,连接busboy。 上传几个文件

[英]nodejs, connect-busboy. Upload few files

I have trouble with events when upload few files through busboy.通过 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

busboy does not emit an end event. busboy不会发出end事件。 The finish event is emitted once the entire request has been processed and all file streams have been completely read.一旦处理了整个请求并且已完全读取所有file流,就会发出finish事件。 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.所以问题是底层文件描述符的关闭发生在下一个滴答(左右),它发生在发出finish之后。

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.如果您需要知道所有文件描述符何时关闭,那么您需要想出一种方法来跟踪发出了多少close事件。

close events are called when the file events are closed.当文件事件关闭时调用 close 事件。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM