nodejs,connect-busboy。上传几个文件

时间:2014-10-02 14:06:42

标签: javascript node.js file-upload busboy

通过busboy上传少量文件时遇到问题。我的代码:

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);
});

我的表格(玉模板)

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

活动'结束'只是忽略了,在文件上传过程中完成了火灾。哪里错了?

服务器控制台报告:

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

2 个答案:

答案 0 :(得分:2)

busboy不会发出end个事件。处理完整个请求并完全读取所有finish流后,将发出file事件。所以问题是底层文件描述符的关闭发生在发出finish之后的下一个tick(或左右)中。

如果您需要知道所有文件描述符何时关闭,那么您需要提供一种方法来跟踪已发出的close个事件。

答案 1 :(得分:0)

close 事件在文件事件关闭时被调用。您可以在文件事件中跟踪文件计数,并可以在关闭事件中使用此计数器查看所有文件何时上传。

以下是您可以尝试的内容

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);