安裝依賴包
import JSZip from'jszip'
import FileSaver from'file-saver'
文件URL轉(zhuǎn)BLOB格式
const fileArrayBuffer = (url) => {
return new Promise((resolve, reject) => {
//通過請求獲取文件blob格式
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.responseType = "blob";
xmlhttp.onload = function () {
if (this.status == 200) { resolve(this.response);
} else { reject(this.status); }
}
xmlhttp.send();
})
}
文件打包下載
const fileZipDownload = (lists, fileName) => {
const zip = new JSZip()
const promises = []
for(let i = 0; i < lists.length; i++) {
const promise= fileArrayBuffer(lists[i]).then(data => {
const fileName = lists[i].split('/').pop()
// 下載文件, 并存成ArrayBuffer對象(blob)
zip.file(fileName, data, { binary: true }) // 逐個添加文件
})
promises.push(promise)
}
Promise.all(promises).then(() => {
zip.generateAsync({ type: "blob" }).then(content => {
// 生成二進(jìn)制流
FileSaver.saveAs(content, fileName); // 利用file-saver保存文件 自定義文件名
console.log('File Zip Success!')
}).catch(res=>{
console.log('File Zip Failed!')
});
})
}
使用~~~
fileZipDownload([
'https://rapiddeals.s3.us-east-2.amazonaws.com/supplier/2021/01/99c8446c-4011-49a4-8092-50ef3b743a99.pdf',
'https://rapiddeals.s3.us-east-2.amazonaws.com/supplier/2021/01/9cd81b8d-81a2-4522-9697-adf23385a09d.pdf'
])