Skip to content

Instantly share code, notes, and snippets.

@renzhezhilu
Created October 14, 2019 14:11
Show Gist options
  • Save renzhezhilu/228d7fd73a3cf6cf9e038ecb52aa582f to your computer and use it in GitHub Desktop.
Save renzhezhilu/228d7fd73a3cf6cf9e038ecb52aa582f to your computer and use it in GitHub Desktop.
[下载多个文件后打包成ZIP再下载] #数据处理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>下载多个文件后打包成ZIP再下载</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jszip/3.2.2/jszip.min.js"></script>
<script>
var urlContentData = {
name: 'k18203',
data: [
`https://photo.weibo.com/5582844844/photos/detail/photo_id/4427061371470073`,
`https://photo.weibo.com/5582844844/photos/detail/photo_id/4427063644782651`,
`https://tvax1.sinaimg.cn/default/images/default_avatar_male_180.gif?KID=imgbed,tva&Expires=1571073032&ssig=ZdK5UIM1K5`
]
}
downloadFile(urlContentData)
function downloadFile(urlContent) {
let zip = new JSZip();
let d_file = []
urlContent.data.map((url,i) => {
setTimeout(() => {
fetch(url).then(x => {
return x.blob()
}).then(b=>{
d_file.push(b)
console.log(`下载完成...${b.size}`)
//下载完成
if (d_file.length === urlContent.data.length) {
d_file.map((imgBlob, index) => {
let fileName = `${urlContent.name}_${index}.jpg`
zip.file(fileName, imgBlob)
})
zip.generateAsync({type:"blob"})
.then(function(content) {
funDownload(content,`${urlContent.name}.zip`)
console.log(`完成✅`)
});
}
})
}, 300*i)
})
function funDownload(content, filename) {
let eleLink = document.createElement('a');
eleLink.download = filename;
eleLink.style.display = 'none';
let blob = new Blob([content]);
eleLink.href = URL.createObjectURL(blob);
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment