import JSZip from 'jszip'
import { saveAs } from 'file-saver'
// 获取文件blob格式
const getFileBlob = (url) => {
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest()
request.open("GET", url, true)
request.responseType = "blob"
request.onload = (res) => {
if (res.target.status == 200) {
resolve(res.target.response)
} else {
reject(res)
}
}
request.send()
})
}
// 多个文件下载
export const downLoadMultiFile = (files,filesName) => {
const zip = new JSZip()
let result = []
for (let i in files) {
let promise = getFileBlob(files[i].url).then((res) => {
zip.file(files[i].name, res, { binary: true })
})
result.push(promise)
}
Promise.all(result).then(() => {
zip.generateAsync({ type: "blob" }).then((res) => {
saveAs(res, filesName ? filesName + Date.now() + '.zip' : `文件夹${Date.now()}.zip`)
})
})
}
// 多个文件夹下载
export const downLoadMultiFolder = (folders,filesName) => {
return new Promise((resolve,reject) => {
const zip = new JSZip()
let promiseAll = []
folders.forEach(fold => {
let folder = zip.folder(fold.name);
let result = []
for (let i in fold.files) {
let promise = getFileBlob(fold.files[i].url).then((res) => {
folder.file(fold.files[i].name, res, { binary: true })
})
result.push(promise)
}
promiseAll.push(Promise.all(result))
});
Promise.all(promiseAll).then(() => {
zip.generateAsync({ type: "blob" }).then((res) => {
resolve()
saveAs(res, filesName ? filesName + Date.now() + '.zip' : `文件夹${Date.now()}.zip`)
})
})
})
}
多文件合并下载使用
import { downLoadMultiFile } from "@/utils"
let files = [{
url: '文件路径',
name: '文件名称'
}]
downLoadMultiFile(files)
多文件夹合并下载使用
import { downLoadMultiFolder } from "@/utils"
let folders = [
{
files :[
{
url: '文件路径',
name: '文件名称'
}
],
name: '文件夹名称'
}
]
downLoadMultiFolder(folders, `文件名`)