使用Dicer将异步数据部分排序到文件中



我正在使用Dicer解析一些上传的图像文件,但我不知道如何将数据分离到特定的文件中。由于Dicer异步解析多部分数据,因此触发事件的时间没有顺序,因此数据可以以任何顺序出现。我已经查看了Dicer对象,似乎没有任何东西可以识别数据部分和它们所属的文件。

骰子示例代码:

var inspect = require('util').inspect,
http = require('http');

var Dicer = require('dicer');

// quick and dirty way to parse multipart boundary
var RE_BOUNDARY = /^multipart/.+?(?:; boundary=(?:(?:"(.+)")|(?:([^s]+))))$/i,
HTML = Buffer.from('<html><head></head><body>
<form method="POST" enctype="multipart/form-data">
<input type="text" name="textfield"><br />
<input type="file" name="filefield"><br />
<input type="submit">
</form>
</body></html>'),
PORT = 8080;

http.createServer(function(req, res) {
var m;
if (req.method === 'POST'
&& req.headers['content-type']
&& (m = RE_BOUNDARY.exec(req.headers['content-type']))) {
var d = new Dicer({ boundary: m[1] || m[2] });

d.on('part', function(p) {
console.log('New part!');
p.on('header', function(header) {
for (var h in header) {
console.log('Part header: k: ' + inspect(h)
+ ', v: ' + inspect(header[h]));
}
});
p.on('data', function(data) {
console.log('Part data: ' + inspect(data.toString()));
});
p.on('end', function() {
console.log('End of partn');
});
});
d.on('finish', function() {
console.log('End of parts');
res.writeHead(200);
res.end('Form submission successful!');
});
req.pipe(d);
} else if (req.method === 'GET' && req.url === '/') {
res.writeHead(200);
res.end(HTML);
} else {
res.writeHead(404);
res.end();
}
}).listen(PORT, function() {
console.log('Listening for requests on port ' + PORT);
});

我终于想明白了

d.on('part', function(p) {
let image = { name: '', mime: '', data: [] };
p.on('header', function(header) {
image.name = header["content-disposition"][0].split('filename="')[1].split('"')[0];
image.mime = header["content-type"][0];
});
p.on('data', function(data) {
image.data.push(data);
});
p.on('end', function() {
time = imageReader.endStreamData(image);
image = null;
});
});
d.on('finish', function() {
//console.log(images);
res.status(200).send({response: 'ok'});
});

最新更新