|
| 1 | +import { useState } from "react"; |
| 2 | + |
| 3 | +/** |
| 4 | + * This hook is used to download a file from a given URL. |
| 5 | + * It handles the download progress and errors. |
| 6 | + * |
| 7 | + * @params fileUrl: The URL of the file to download. |
| 8 | + * @params fileName: The name of the file to download. |
| 9 | + * @params response: A function that returns a promise that resolves to a Response object. |
| 10 | + */ |
| 11 | +export const useDownload = (fileUrl: string, fileName: string, response?: () => Promise<Response>) => { |
| 12 | + const [error, setError] = useState<Error | unknown | null>(null); |
| 13 | + const [isDownloading, setIsDownloading] = useState<boolean>(false); |
| 14 | + const [progress, setProgress] = useState<number | null>(null); |
| 15 | + |
| 16 | + const handleResponse = async (response: Response): Promise<string> => { |
| 17 | + if (!response.ok) { |
| 18 | + throw new Error("Could not download file"); |
| 19 | + } |
| 20 | + |
| 21 | + const contentLength = response.headers.get("content-length"); |
| 22 | + const reader = response.body?.getReader(); |
| 23 | + |
| 24 | + if (!contentLength || !reader) { |
| 25 | + const blob = await response.blob(); |
| 26 | + |
| 27 | + return createBlobURL(blob); |
| 28 | + } |
| 29 | + |
| 30 | + const stream = await getStream(contentLength, reader); |
| 31 | + const newResponse = new Response(stream); |
| 32 | + const blob = await newResponse.blob(); |
| 33 | + |
| 34 | + return createBlobURL(blob); |
| 35 | + }; |
| 36 | + |
| 37 | + const getStream = async (contentLength: string, reader: ReadableStreamDefaultReader<Uint8Array>): Promise<ReadableStream<Uint8Array>> => { |
| 38 | + let loaded = 0; |
| 39 | + const total = parseInt(contentLength, 10); |
| 40 | + |
| 41 | + return new ReadableStream<Uint8Array>({ |
| 42 | + async start(controller) { |
| 43 | + try { |
| 44 | + for (;;) { |
| 45 | + const { done, value } = await reader.read(); |
| 46 | + |
| 47 | + if (done) break; |
| 48 | + |
| 49 | + loaded += value.byteLength; |
| 50 | + const percentage = Math.trunc((loaded / total) * 100); |
| 51 | + setProgress(percentage); |
| 52 | + controller.enqueue(value); |
| 53 | + } |
| 54 | + } catch (error) { |
| 55 | + controller.error(error); |
| 56 | + throw error; |
| 57 | + } finally { |
| 58 | + controller.close(); |
| 59 | + } |
| 60 | + }, |
| 61 | + }); |
| 62 | + }; |
| 63 | + |
| 64 | + const createBlobURL = (blob: Blob): string => { |
| 65 | + return window.URL.createObjectURL(blob); |
| 66 | + }; |
| 67 | + |
| 68 | + const handleDownload = (fileName: string, url: string) => { |
| 69 | + const link = document.createElement("a"); |
| 70 | + |
| 71 | + link.href = url; |
| 72 | + link.setAttribute("download", fileName); |
| 73 | + document.body.appendChild(link); |
| 74 | + link.click(); |
| 75 | + document.body.removeChild(link); |
| 76 | + window.URL.revokeObjectURL(url); |
| 77 | + }; |
| 78 | + |
| 79 | + const downloadFile = async () => { |
| 80 | + setIsDownloading(true); |
| 81 | + setError(null); |
| 82 | + setProgress(null); |
| 83 | + |
| 84 | + try { |
| 85 | + const res = response ? await response() : await fetch(fileUrl); |
| 86 | + const url = await handleResponse(res); |
| 87 | + |
| 88 | + const headerFileName = res.headers.get("content-disposition")?.match(/filename="(.+)"/)?.[1]; |
| 89 | + |
| 90 | + handleDownload(headerFileName || fileName, url); |
| 91 | + } catch (error) { |
| 92 | + setError(error); |
| 93 | + } finally { |
| 94 | + setIsDownloading(false); |
| 95 | + } |
| 96 | + }; |
| 97 | + |
| 98 | + return { |
| 99 | + error, |
| 100 | + isDownloading, |
| 101 | + progress, |
| 102 | + downloadFile, |
| 103 | + }; |
| 104 | +}; |
0 commit comments