【问题标题】:nodejs + archiver, Why this zip archive downloader does not work (Unexpected end of archive)?nodejs + 存档器,为什么这个 zip 存档下载器不起作用(存档意外结束)?
【发布时间】:2016-02-29 08:10:46
【问题描述】:

我想使用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');
    });

【问题讨论】:

    标签: javascript node.js express zip


    【解决方案1】:

    我忘了设置正确的响应类型: responseType: 'arraybuffer'

    【讨论】:

      【解决方案2】:

      看来您需要等到最终确定完成。 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 承诺解决后等待更好的方法

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        相关资源
        最近更新 更多