如何使用busboy上传base64数据

How can use busboy upload base64 data

例如:
1. Test1.txt 其base64:VGhpcyBpcyB0ZXN0MS4=
2. Test2.txt其base64:VGhpcyBpcyBUZXN0Mi4=

我的代码:

req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    console.log('File: ' + filename + ', mimetype: ' + mimetype);
    file.pipe(base64.encode()).pipe(output);
    var i = 0;
    output.on('data', function(data) {
    console.log('File [' + filename + '] size: ' + data.length + ' bytes');
    base64data[i] = data;
    i++;
    });
    output.on('end', function(){
        console.log('Data: ' + base64data);
    });
});

输出:
文件:Test1.txt,模仿类型:text/plain
文件:Test2.txt,模仿类型:text/plain
文件 [Test1.txt] 大小:16 字节
文件 [Test2.txt] 大小:16 字节
文件 [Test1.txt] 大小:16 字节
文件 [Test2.txt] 大小:16 字节
文件 [Test1.txt] 大小:4 字节
文件 [Test2.txt] 大小:4 字节
文件 [Test1.txt] 大小:4 字节
文件 [Test2.txt] 大小:4 字节
数据:VGhpcyBpcyB0ZXN0,VGhpcyBpcyBUZXN0,MS4=,Mi4=
数据:VGhpcyBpcyB0ZXN0,VGhpcyBpcyBUZXN0,MS4=,Mi4=

这个结果不正确。我想要正确的结果:
Data:VGhpcyBpcyB0ZXN0MS4=,VGhpcyBpcyBUZXN0Mi4=
如何修改此代码?求助!

参考robertklep的代码:

var base64data = [];
var chunks = [];
var output = new stream.PassThrough();

req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    console.log('File: ' + filename + ', mimetype: ' + mimetype);
    file.pipe(base64.encode()).pipe(output);
    output.on('data', function(data) {
        chunks.push(data);
        console.log('Chunks: ' + chunks);
    });
    output.on('end', function(){
        base64data.push(Buffer.concat(chunks));
        console.log('Data1: ' + base64data);
    });
}).on('finish', function(){
    console.log('Data2:' + base64data)
});

输出:

File: Test1.txt, mimetype: text/plain
File: Test2.txt, mimetype: text/plain
Chunks: VGhpcyBpcyB0ZXN0
Chunks: VGhpcyBpcyB0ZXN0,VGhpcyBpcyB0ZXN0
Chunks: VGhpcyBpcyB0ZXN0,VGhpcyBpcyB0ZXN0,VGhpcyBpcyBUZXN0
Chunks: VGhpcyBpcyB0ZXN0,VGhpcyBpcyB0ZXN0,VGhpcyBpcyBUZXN0,VGhpcyBpcyBUZXN0
Chunks: VGhpcyBpcyB0ZXN0,VGhpcyBpcyB0ZXN0,VGhpcyBpcyBUZXN0,VGhpcyBpcyBUZXN0,
MS4=
Chunks: VGhpcyBpcyB0ZXN0,VGhpcyBpcyB0ZXN0,VGhpcyBpcyBUZXN0,VGhpcyBpcyBUZXN0,
MS4=,MS4=
Chunks:VGhpcyBpcyB0ZXN0,VGhpcyBpcyB0ZXN0,VGhpcyBpcyBUZXN0,VGhpcyBpcyBUZXN0,
MS4=,MS4=,Mi4=
Chunks: VGhpcyBpcyB0ZXN0,VGhpcyBpcyB0ZXN0,VGhpcyBpcyBUZXN0,VGhpcyBpcyBUZXN0,
MS4=,MS4=,Mi4=,Mi4=
Data2:
Data1: VGhpcyBpcyB0ZXN0VGhpcyBpcyB0ZXN0VGhpcyBpcyBUZXN0VGhpcyBpcyBUZXN0
MS4=MS4=Mi4=Mi4=
Data1: VGhpcyBpcyB0ZXN0VGhpcyBpcyB0ZXN0VGhpcyBpcyBUZXN0VGhpcyBpcyBUZXN0
MS4=MS4=Mi4=Mi4=,VGhpcyBpcyB0ZXN0VGhpcyBpcyB0ZXN0VGhpcyBpcyBUZXN0VGhpcy
BpcyBUZXN0MS4=MS4=Mi4=Mi4=

您正在将属于不同文件的块推送到同一个数组中,而且,您需要等待 所有 个文件处理完毕,然后才能按照您的意愿进行记录:

var base64data = [];

req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
  file.pipe(base64.encode()).pipe(output);
  var chunks = [];
  output.on('data', function(data) {
    chunks.push(data);
  });
  output.on('end', function(){
    base64data.push(Buffer.concat(chunks));
  });
}).on('finish', function() {
  console.log('Data: ' + base64data);
});