将Ajax响应下载为zip文件?

时间:2018-08-30 14:07:00

标签: javascript node.js express zip blob

我正在尝试将多个图像下载为zip文件。当我使用Azure blob时,首先列出所有blob,然后使用Archiver对其进行压缩,然后使用管道功能将其发送到客户端。但是我将zip作为原始文件获取,并且没有下载。我正在使用Node js + Express。 服务器端脚本:

    function zipURLs(urls, outStream) {
  var zipArchive = archiver.create('zip');

  async.eachLimit(urls, 3, function(url, done) {
    console.log(url);
    var stream = request.get(url);

    stream.on('error', function(err) {
      return done(err);
    }).on('end', function() {
      return done();
    });

    // Use the last part of the URL as a filename within the ZIP archive.
    zipArchive.append(stream, { name : url.replace(/^.*\//, '') });
  }, function(err) {
    if (err) throw err;
    zipArchive.finalize();
    zipArchive.pipe(outStream);


  });
}
var data = {}; 
data.blob_name = value; 
console.log('downloading'); 
$.ajax({ 
    type: 'POST', 
    data: JSON.stringify(data),  
    contentType: 'application/json', 
    url: 'download/', 
    success: function(data) { console.log(data); }

上游是资源。所以我得到这样的数据:-

enter image description here

如何使用js直接下载为zip文件?

谢谢

1 个答案:

答案 0 :(得分:0)

使用ajax下载文件有很多事情,首先,您必须能够通过将responseType设置为blob来访问二进制(不是默认值的文本)数据。 然后,您必须实际使用一种方法来显示下载对话框,您可以在下面看到具有下载属性技术的锚点。

jQuery.ajax({
        url:'download/',
        type:'POST',
        data: JSON.stringify(data),  
        contentType: 'application/json', 
        xhrFields:{
            responseType: 'blob'
        },
        success: function(data){
            var anchor = document.getElementById('a');
            var url = window.URL || window.webkitURL;
            anchor.href = url.createObjectURL(data);
            anchor.download = 'archive.zip';
            document.body.append(anchor);
            anchor.click();
            setTimeout(function(){  
                document.body.removeChild(anchor);
                url.revokeObjectURL(anchor.href);
            }, 1};
        },
        error:function(){

        }
    });

需要jQuery3 +

相关问题