是否可以在 javascript 中将多个下载 url 发送到一个 zip 文件中,并且可以下载该 zip 文件。非常多,在我的网页上,有一个按钮,单击该按钮时会从下载 url 中下载所有文件的 zip 文件,并将其压缩为 zip 文件?
我相信我需要使用 jszip 或类似的工具。这完全可能吗?有什么关于从哪里开始的建议吗?
是否可以在 javascript 中将多个下载 url 发送到一个 zip 文件中,并且可以下载该 zip 文件。非常多,在我的网页上,有一个按钮,单击该按钮时会从下载 url 中下载所有文件的 zip 文件,并将其压缩为 zip 文件?
我相信我需要使用 jszip 或类似的工具。这完全可能吗?有什么关于从哪里开始的建议吗?
您可以使用JSZip.js
, XMLHttpRequest()
, Array.prototype.map()
,在所有文件请求完成后Promise.all()
创建.zip
文件;使用<a>
带有元素download
属性设置为objectURL
中.zip
在文件JSZip
.generateAsync()
功能,点击a
元素应该显示Save File
对话框,创建.zip
可下载的文件。
<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>
我最近不得不解决同样的问题,并找到了使用JSZipUtils的解决方案。
可以在此处找到解决方案http://plnkr.co/edit/vWARo0dXbkgzmjyoRNi0?p=preview
我有两个文件,我想通过用户浏览器压缩和下载它们,我getBinaryContent(path, callback)
在这两个文件上调用了该函数。这里的路径是文件的存储位置。
这两个文件是 .wav 文件和 .json 文件。它们中的每一个都应该被区别对待,因此您应该{base64:true,binary:true}
将 .wav 文件和{binary:true}
json 文件用作JSZip函数文件的参数。
代码也可以在这里找到
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);
})