我想以zip文件的形式下载数据库中的所有文件。动态创建多个文件nodejs
如果我只想下载元素,我可以很容易地设置它的头和内容类型,然后可以发送它的缓冲区。
db.collection("resource").find({}).toArray(function(err, result) {
res.setHeader('Content-disposition', 'attachment; filename=' + result[0].name);
res.contentType(result[0].mimetype);
res.send(result[0].data.buffer);
}
现在我想创建一个文件夹和每个result
元素添加到该文件夹,然后将其发送。
以下代码仅返回第一个文件。这是合理的,因为我立即发送缓冲区。
for(var i=0; i < result.length; i++){
res.setHeader('Content-disposition', 'attachment; filename=' + result[i].name);
res.send(result[i].data.buffer);
}
我想将它们添加到数组中。
for(var i=0; i < result.length; i++){
var obj = {name: result[i].name, buffer: result[i].data.buffer};
files.push(obj);
}
res.setHeader('Content-disposition', 'attachment; filename=' + "resource");
res.contentType('application/zip');
res.send(files);
这回我一个文本文件resource
其中包括name
和buffer
为JSON格式。
即使我将contentType更新为application/zip,它将以文本格式返回。
如何创建此文件,添加到文件夹并将文件夹类型设置为zip?