Multiple download links to one zip file before download javascript

前端 未结 2 1365
星月不相逢
星月不相逢 2020-11-27 06:42

Is it possible, in javascript, to have multiple download urls sent into one zip file and that zip file can be downloaded. So pretty much, on my web page, there is one button

2条回答
  •  春和景丽
    2020-11-27 07:31

    I recently had to solve the same issue and had found a solution using JSZipUtils.

    The solution can be found here http://plnkr.co/edit/vWARo0dXbkgzmjyoRNi0?p=preview

    I have two files that I would like to zip and download via the users browser and I call the function getBinaryContent(path, callback) on both files. The path here is the where the file is stored.

    The two files are a .wav file and a .json file. Each of them should be treated differenly and hence you should use {base64:true,binary:true} for the .wav file and {binary:true} for the json file as an argument for the function file of JSZip.

    The code can be found here as well

    var file_confirmation=[false,false];
    var file_name=["test1.wav","test.json"];
    var urlList =["test.wav","test.json"];
    
    var filenameSave ="myZip";
    
    
    function zipFiles(id,urls)
    {
        zip = new JSZip();
    
    JSZipUtils.getBinaryContent(urls[0],function (err, data) 
    {
        if(!err)
        {
            var dic={base64:true,binary:true}; //WAV File Encoding
            zip.file(file_name[0], data, dic);
            file_confirmation[0]=true;
            downloadZipIfAllReady(id);
        }
    });
    
    JSZipUtils.getBinaryContent(urls[1],function (err, data) 
        {
            if(!err)
            {
                var dic={binary:true}; //JSON File Encoding
                zip.file(file_name[1], data, dic);
                file_confirmation[1]=true;
                downloadZipIfAllReady(id);
            }
        });
    }    
    
    function downloadZipIfAllReady(id)
        {
            if(file_confirmation.every(function(element, index, array) {return element;}))
            {
                 zip.generateAsync({type:"blob"})
                    .then(function(content)
                    {
                      var a = document.querySelector("#"+id);
                      a.download = filenameSave;
                      a.href = URL.createObjectURL(content);
                      a.click();
                });
        }
    }
    
    
    $(document).ready(function()
    {
    
     zipFiles("a_id",urlList);
    
    })
    

提交回复
热议问题