onClickDownloadBtn(row) {
// TODO: delete Demo Data
const files = [
{
id: 1,
name: '1file',
isFile: false,
children: [
{
id: 11,
name: '1-1file',
isFile: false,
children: [
{
id: 111,
name: '1-1-1file',
isFile: true,
url: 'https://im-1305783521.cos.ap-guangzhou.myqcloud.com/im/file/lilinjian/1641631041478/dd.txt'
}
]
}, {
id: 12,
name: '1-2file',
isFile: true,
url: 'https://im-1305783521.cos.ap-guangzhou.myqcloud.com/im/file/C13012345678/1641805597561/巴达兽.png'
}
]
}, {
id: 2,
name: '2file',
isFile: true,
url: 'https://im-1305783521.cos.ap-guangzhou.myqcloud.com/im/file/C13012345678/1645261335302/测试文档.doc'
}, {
id: 3,
name: '3folder',
isFile: false,
}
]
const zip = new JSZip()
let result = []
files.forEach((file) => {
this.addFileOrFolder(file, '', zip, result);
})
Promise.all(result).then(() => {
zip.generateAsync({ type: "blob" }).then((res) => {
saveAs(res, row.title + ".zip")
})
})
}
addFileOrFolder(file, prefix, zip, result) {
let fileName = file.name;
if (prefix) {
fileName = prefix + '/' + file.name;
}
if (!file.isFile) {
if (file.children && file.children.length) {
file.children.forEach((subFile) => {
this.addFileOrFolder(subFile, fileName, zip, result);
});
} else {
zip.folder(fileName);
}
} else {
let promise = this.getFileBlob(file.url).then((res) => {
let format = file.url.substring(file.url.lastIndexOf("."), file.url.length)
zip.file(fileName + format, res, { binary: true })
})
result.push(promise);
}
}
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()
})
}
React 下载树形结构文件目录压缩包
最新推荐文章于 2023-12-18 16:23:59 发布