From 1d6c40affea87d2df9900ff8ba66f976ec1aef9a Mon Sep 17 00:00:00 2001 From: myl7 Date: Sat, 27 Nov 2021 16:26:22 +0800 Subject: [PATCH] update download function Rename it and turn it into async other than using callback --- components/FileListing.tsx | 6 +++--- utils/tools.ts | 27 +++++++++++---------------- 2 files changed, 14 insertions(+), 19 deletions(-) diff --git a/components/FileListing.tsx b/components/FileListing.tsx index 6e70c4c..ece6fb8 100644 --- a/components/FileListing.tsx +++ b/components/FileListing.tsx @@ -242,7 +242,7 @@ const FileListing: FunctionComponent<{ query?: ParsedUrlQuery }> = ({ query }) = } // Selected file download - const handleDownloadSelected = () => { + const handleSelectedDownload = () => { const folderName = path.substr(path.lastIndexOf('/') + 1) const folder = folderName ? folderName : undefined const files = getFiles() @@ -257,7 +257,7 @@ const FileListing: FunctionComponent<{ query?: ParsedUrlQuery }> = ({ query }) = el.remove() } else if (files.length > 1) { setTotalGenerating(true) - saveFiles(files, folder, () => setTotalGenerating(false)) + saveFiles(files, folder).then(() => setTotalGenerating(false)) } } @@ -302,7 +302,7 @@ const FileListing: FunctionComponent<{ query?: ParsedUrlQuery }> = ({ query }) = diff --git a/utils/tools.ts b/utils/tools.ts index 3ad0986..e134db5 100644 --- a/utils/tools.ts +++ b/utils/tools.ts @@ -129,26 +129,21 @@ export const matchProtectedRoute = (route: string) => { * Download multiple files after compressing them into a zip * @param files Files to be downloaded * @param folder Optional folder name to hold files, otherwise flatten files in the zip - * @param onFinish Optional hook triggered after sending generated zip to browser to download */ -export const saveFiles = (files: { name: string, url: string }[], folder?: string, onFinish?: () => void) => { +export const saveFiles = async (files: { name: string, url: string }[], folder?: string) => { const zip = new JSZip() const dir = folder ? zip.folder(folder)! : zip files.forEach(({ name, url }) => { dir.file(name, fetch(url).then(r => r.blob())) }) - dir.generateAsync({ type: 'blob' }).then(b => { - const el = document.createElement('a') - el.style.display = 'none' - document.body.appendChild(el) - const bUrl = window.URL.createObjectURL(b) - el.href = bUrl - el.download = folder ? folder + '.zip' : 'download.zip' - el.click() - window.URL.revokeObjectURL(bUrl) - el.remove() - if (onFinish) { - onFinish() - } - }) + const b = await dir.generateAsync({ type: 'blob' }) + const el = document.createElement('a') + el.style.display = 'none' + document.body.appendChild(el) + const bUrl = window.URL.createObjectURL(b) + el.href = bUrl + el.download = folder ? folder + '.zip' : 'download.zip' + el.click() + window.URL.revokeObjectURL(bUrl) + el.remove() }