File upload
Pick a file and send it to httpbin, which echoes the file back. Two progress bars follow the request: one while the file is being sent, one while the answer is downloaded. Cancel stops the request at any point.
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";
/** httpbin echoes everything it receives, including the uploaded file. */
export const client = createClient({ url: "https://httpbin.org" });
type EchoResponse = {
files: Record<string, string>;
form: Record<string, string>;
headers: Record<string, string>;
};
/** A `FormData` payload is sent as is: the browser sets the multipart `Content-Type` with its boundary. */
export const uploadFileRequest = client.createRequest<{
response: EchoResponse;
payload: FormData;
}>()({
endpoint: "/post",
method: "POST",
});
npx tiged BetterTyped/hyper-fetch/examples/react/file-upload hyper-fetch-react-file-upload && cd hyper-fetch-react-file-upload && npm install && npm run devFormDatapayload: typed aspayload: FormDataand sent without JSON encoding.- Lifecycle callbacks:
onSubmitRequestStart,onSubmitResponseStartandonSubmitDownloadProgressdrive the UI. - Real download progress:
progress,loadedandtotalcome from the response stream. - Cancel:
abort()fromuseSubmitstops the running request and firesonSubmitAbort.
How it works
-
api.tscreates a client forhttps://httpbin.organduploadFileRequestwithpayload: FormData. The default adapter sendsFormData,BlobandArrayBufferpayloads as they are and does not add a JSONContent-Type, so the browser writes the multipart header with its boundary. -
handleSubmitbuilds theFormDataand callsupload.submit({ payload }). -
The callbacks map the request lifecycle to a phase:
onSubmitRequestStartstarts the "Sending" bar,onSubmitResponseStartmeans the server has the file, andonSubmitDownloadProgressfills the "Receiving" bar:upload.onSubmitDownloadProgress(({ progress, loaded, total }) => setReceived({ progress, loaded, total })); -
Cancel calls
upload.abort(). The request is removed from the dispatcher, its network call is aborted andonSubmitAbortruns. The hook keeps no response from the canceled call.
The default adapter uses the browser fetch() API, which does not report how much of the request body was sent. That is
why the "Sending" bar is indeterminate. onSubmitUploadProgress still fires, but only at the start and end of the
request. For a real upload percentage, use the Axios adapter, which uses
XMLHttpRequest in the browser.
- Avatar, document and attachment uploads.
- Any long request where the user should see that something is happening and be able to stop it.
Related
useSubmit sends a FormData payload as it is. Its lifecycle callbacks report when the file goes out and how the
answer comes back, and abort() cancels the upload.
