Download progress
A download button with a progress bar, the speed and the time left. httpbin sends a 1 MB file slowly on purpose; pick how slowly. When the file is complete, Save file stores it from memory without downloading it again.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { createClient } from "@hyper-fetch/core";
export const client = createClient({ url: "https://httpbin.org" });
/** 1 MB, the largest file httpbin's `/range` endpoint sends. */
export const fileSize = 1024 * 1024;
/**
* httpbin sends `:size` letters spread over `duration` seconds, with a `Content-Length` header, so the percentage is
* exact. The default fetch adapter reads the body chunk by chunk and reports each chunk as download progress.
*/
export const downloadFileRequest = client.createRequest<{
response: string;
queryParams: { duration: number; chunk_size: number };
}>()({
endpoint: "/range/:size",
// A download is used once. Keeping a 1 MB string in the cache would only use memory.
cache: false,
// The fetch adapter's timeout (5 s by default) covers the whole download. A slow file needs more.
options: { timeout: 60_000 },
});
npx tiged BetterTyped/hyper-fetch/examples/react/download-progress hyper-fetch-react-download-progress && cd hyper-fetch-react-download-progress && npm install && npm run devonSubmitDownloadProgressfires for every received chunk withprogress,loaded,totalandtimeLeft.- The default fetch adapter reports download progress by reading the response body chunk by chunk.
- A Blob URL turns the response into a file the user can save.
- Request options for downloads:
cache: falseand a longer adaptertimeout.
How it works
-
api.tspointsdownloadFileRequestat httpbin's/range/:size, which sendssizeletters spread overdurationseconds and setsContent-Length. With a known length,progressis an exact percentage. -
Two request options matter for downloads:
client.createRequest<{ response: string; queryParams: { duration: number; chunk_size: number } }>()({endpoint: "/range/:size",cache: false,options: { timeout: 60_000 },});The fetch adapter's timeout covers the whole download and defaults to 5 seconds.
cache: falsekeeps the file out of the cache, since it is used once. -
App.tsxusesuseSubmit, because the download starts on a click.submit({ queryParams })passes the chosen duration. -
onSubmitDownloadProgressstores the numbers from each event. The speed isloadeddivided by the seconds sincestartTimestamp, andtimeLeftcomes from HyperFetch. -
onSubmitSuccesswraps the body in aBloband creates an object URL for the Save file link. The effect cleanup revokes the old URL, so the memory is freed. -
Cancel calls
abort(). The fetch is aborted andonSubmitAbortfires.
The default fetch adapter decodes the response body as text. That is right for JSON and text files like this one, but a
binary file such as an image or a zip would be damaged. For binary downloads with progress, use the Axios adapter with
options: { responseType: "blob" }. Another option is the fetch adapter's streaming: true, which hands you the raw
body stream to read yourself.
- Exports, reports, datasets and media that take more than a moment to arrive.
- Use
onDownloadProgressinsend()oronDownloadProgressfromuseFetchthe same way when the data is read on mount instead of on a click.
Related
The fetch adapter reads the body in chunks and reports each one, so onSubmitDownloadProgress can drive a progress bar,
a speed and a time left. When the response is complete, a Blob URL lets the user save it.
