我想使用archiver + express
下载多个文件。服务器应发送.zip
文件以响应来自客户端的post
请求。
以下代码创建一个zip存档,发送它,向用户显示另存为对话框并让他打开存档。默认情况下,WinRAR打开存档并列出文件(只有一个文件),带有! 98I9ZOCR.zip:意外的归档结束错误。
有什么问题?
服务器:
var archive = archiver('zip');
archive.on('error', function(err) {
res.status(500).send({error: err.message});
});
//on stream closed we can end the request
archive.on('end', function() {
console.log('Archive wrote %d bytes', archive.pointer());
});
//set the archive name
res.attachment('userarchive.zip');
//this is the streaming magic
archive.pipe(res);
for (var fi in req.body.filename) {
var _file = src + '/' + req.body.filename[fi];
archive.file(_file, { name: p.basename(_file) });
}
archive.finalize();
客户端:
$http({
method: 'post',
url: to,
data: data
}).success(function(data, status, headers, config){
var file = new Blob([data], {type: 'application/zip'});
window.location = URL.createObjectURL(file);
}).error(function(data, status, headers, config){
console.log('Error');
});
答案 0 :(得分:0)
我忘了设置正确的响应类型:
responseType: 'arraybuffer'
答案 1 :(得分:0)
似乎您需要等待最终完成。 archive.finalize();
方法返回一个诺言。
在这里,您正在监听“结束”事件,但未按照评论中的说明结束请求
//on stream closed we can end the request
archive.on('end', function() {
console.log('Archive wrote %d bytes', archive.pointer());
});
此外,我发现即使从archive.finalize()
方法返回的诺言得以解决,存档器仍可能会传递一些数据。在finalize
承诺得到解决之后,我没有比等待其他更好的方法了