Multiple download links to one zip file before download javascript
You can use JSZip.js
, XMLHttpRequest()
, Array.prototype.map()
, Promise.all()
to create .zip
file when all requests for files have completed; use <a>
element with download
attribute set to objectURL
of .zip
file at JSZip
.generateAsync()
function, click on a
element should display Save File
dialog with created .zip
as downloadable file.
<head>
<script src="jszip.js"></script>
<script>
window.onload = function() {
var zip = new JSZip();
var a = document.querySelector("a");
var urls = ["a.html", "b.html"];
function request(url) {
return new Promise(function(resolve) {
var httpRequest = new XMLHttpRequest();
httpRequest.open("GET", url);
httpRequest.onload = function() {
zip.file(url, this.responseText);
resolve()
}
httpRequest.send()
})
}
Promise.all(urls.map(function(url) {
return request(url)
}))
.then(function() {
console.log(zip);
zip.generateAsync({
type: "blob"
})
.then(function(content) {
a.download = "folder" + new Date().getTime();
a.href = URL.createObjectURL(content);
a.innerHTML = "download " + a.download;
});
})
}
</script>
</head>
<body>
<a href="" download>download</a>
</body>
plnkr http://plnkr.co/edit/baPtkILg927DtJfh4b5Y?p=preview
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);
})