diff options
author | metamuffin <metamuffin@disroot.org> | 2022-10-26 23:54:33 +0200 |
---|---|---|
committer | metamuffin <metamuffin@disroot.org> | 2022-10-26 23:54:33 +0200 |
commit | 2a83c8bdbdd5a67b6068420520e83524f4a6f6bd (patch) | |
tree | 8638903b93eb929ca74e5027a1816820ff0bc346 /client-web/source/sw/download_stream.ts | |
parent | d0162d41438c7ee3d9bc5321f73ed33defc443a3 (diff) | |
download | keks-meet-2a83c8bdbdd5a67b6068420520e83524f4a6f6bd.tar keks-meet-2a83c8bdbdd5a67b6068420520e83524f4a6f6bd.tar.bz2 keks-meet-2a83c8bdbdd5a67b6068420520e83524f4a6f6bd.tar.zst |
some code for streamed downloads
Diffstat (limited to 'client-web/source/sw/download_stream.ts')
-rw-r--r-- | client-web/source/sw/download_stream.ts | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/client-web/source/sw/download_stream.ts b/client-web/source/sw/download_stream.ts new file mode 100644 index 0000000..4eaf382 --- /dev/null +++ b/client-web/source/sw/download_stream.ts @@ -0,0 +1,57 @@ +import { SW } from "./init.ts" + +// export function StreamDownload(size: number, filename?: string, progress?: (position: number) => void) { +// let position = 0 +// const buffer = new Uint8Array(size) +// return { +// close() { +// const a = document.createElement("a") +// a.href = URL.createObjectURL(new Blob([buffer], { type: "text/plain" })) +// a.download = filename ?? "file" +// a.click() +// }, +// write(chunk: Blob) { +// const reader = new FileReader(); +// reader.onload = function (event) { +// const arr = new Uint8Array(event.target!.result as ArrayBuffer); +// for (let i = 0; i < arr.length; i++, position++) { +// buffer[position] = arr[i] +// } +// if (progress) progress(position) +// }; +// reader.readAsArrayBuffer(chunk); +// } +// } +// } + +export function StreamDownload(size: number, filename?: string, progress?: (position: number) => void) { + let position = 0 + + const path = `/download/${encodeURIComponent(filename ?? "file")}` + + const { port1, port2 } = new MessageChannel() + SW!.postMessage({ path, size }, [port2]) + + const a = document.createElement("a") + a.href = path + a.download = filename ?? "file" + a.target = "_blank" + a.click() + + return { + close() { + port1.postMessage("end") + }, + write(chunk: Blob) { + const reader = new FileReader(); + reader.onload = function (event) { + const arr = new Uint8Array(event.target!.result as ArrayBuffer); + console.log("send", arr); + port1.postMessage(arr) + position += arr.length + if (progress) progress(position) + }; + reader.readAsArrayBuffer(chunk); + } + } +} |