# DownloadButton (/docs/download-button)





`DownloadButton` saves a file when it is clicked. Give it the file as `data`: a `Blob` you already have, a URL, or a function that resolves one of those on click. While a function's promise is pending, the button shows a spinner and ignores further clicks, so a double click saves one file.

The kit never makes a request. Fetching with a token, asking the API for a presigned link or building a CSV happens in your function, which receives an `AbortSignal`.

```tsx
import { DownloadButton } from '@42-central/ui-react/download-button';

<DownloadButton
  name="transcript.pdf"
  data={({ signal }) => api.get(`/transcripts/${id}`, { signal }).then((r) => r.blob())}
/>
```

## Playground [#playground]

<story.Playground />

## A Blob [#a-blob]

A `Blob` (or a `File`) is saved inside the click, under `name`. It renders a kit [`Button`](/docs/button) and takes its props: `variant`, `color`, `size`, `endSlot`. The label defaults to "Download" (`translations.label`), and the leading icon is `icons.download`.

<Preview code="&#x22;const notes = new Blob(['Interview notes…'], { type: 'text/plain' });\n\n<DownloadButton data={notes} name=\&#x22;interview-notes.txt\&#x22; />&#x22;">
  <DownloadButtonBlobDemo />
</Preview>

## A generated CSV [#a-generated-csv]

Pass a function to build the file on click rather than on every render. A function may return the Blob directly; nothing waits then.

<Preview code="&#x22;const toCsv = (rows: string[][]) =>\n  new Blob(['\\uFEFF', rows.map((row) => row.map(cell).join(',')).join('\\n')], {\n    type: 'text/csv;charset=utf-8', // the BOM lets Excel read accents\n  });\n\n<DownloadButton\n  data={() => toCsv(rows)}\n  name=\&#x22;grades.csv\&#x22;\n  variant=\&#x22;light\&#x22;\n  color=\&#x22;brand\&#x22;\n  icons={{ download: <FileSpreadsheet className={iconStroke} /> }}\n>\n  Export CSV\n</DownloadButton>&#x22;">
  <DownloadButtonCsvDemo />
</Preview>

## An authenticated fetch [#an-authenticated-fetch]

A bare link can't carry a bearer token, so fetch the file yourself and return the Blob. While the promise is pending, the button is busy: a spinner replaces the icon, `aria-busy="true"` is set, and its name gains "Preparing download…". It stays enabled and keeps focus, so a keyboard user isn't thrown back to the top of the page. Clicks are ignored until the promise settles.

The demo waits 2.5 seconds to stand in for a slow server.

<Preview code="&#x22;<DownloadButton\n  name=\&#x22;transcript.pdf\&#x22;\n  variant=\&#x22;outline\&#x22;\n  data={async ({ signal }) => {\n    const response = await fetch(`/api/transcripts/${id}`, {\n      headers: { Authorization: `Bearer ${token}` },\n      signal,\n    });\n    if (!response.ok) throw new Error(response.statusText);\n    return response.blob();\n  }}\n>\n  Download transcript\n</DownloadButton>&#x22;">
  <DownloadButtonFetchDemo />
</Preview>

Check `response.ok`: `fetch` resolves on a 404 too, and its error page would be saved as `transcript.pdf`.

If the button unmounts before the promise settles (the user navigates away, the dialog closes), `signal` aborts and nothing is saved afterwards. Pass it on to `fetch` so the request stops too.

## A presigned URL [#a-presigned-url]

Return a URL instead of a Blob, and the browser downloads it itself: no memory held, and the browser's own progress UI for a large file. The demo's "API" answers after 0.6 seconds with a file served by this site.

<Preview code="&#x22;<DownloadButton\n  name=\&#x22;grades.csv\&#x22;\n  variant=\&#x22;subtle\&#x22;\n  data={async ({ signal }) => {\n    const { url } = await api.get(`/templates/${id}/download`, { signal });\n    return url;\n  }}\n>\n  Download the template\n</DownloadButton>&#x22;">
  <DownloadButtonPresignedDemo />
</Preview>

<Callout type="warning" title="Filenames from presigned URLs">
  Browsers ignore `name` on a cross-origin URL, such as an S3 presigned link: the `download` attribute only applies to same-origin, `blob:` and `data:` URLs. The file is named by the response's `Content-Disposition` header, and without `attachment` the browser opens the file instead of saving it. The fix is on the server: send `Content-Disposition: attachment; filename*=UTF-8''<encoded name>`. An S3 presign can set it per link with `ResponseContentDisposition`. This is a request for your backend or API team; the kit won't fetch the file to rename it.
</Callout>

## Icon-only, in a row [#icon-only-in-a-row]

With `asChild`, only the behaviour goes onto your element: the click, `aria-busy` and `data-loading`, `disabled`, `testId`. Use it to make an [`ActionIcon`](/docs/action-icon) a download button in a [`FileItem`](/docs/file-item)'s `actions`. Button's styling isn't added, so style the child; while busy, the spinner stands in for its icon.

An icon has no text, so give the child an `aria-label` that names the file.

<Preview align="block" code="&#x22;<FileItem\n  file={document}\n  actions={\n    <DownloadButton asChild name={document.name} data={({ signal }) => fetchDocument(document.id, signal)}>\n      <ActionIcon variant=\&#x22;subtle\&#x22; color=\&#x22;neutral\&#x22; size=\&#x22;xs\&#x22; aria-label={`Download ${document.name}`}>\n        <Download className={iconStroke} aria-hidden />\n      </ActionIcon>\n    </DownloadButton>\n  }\n/>&#x22;">
  <DownloadButtonFileItemDemo />
</Preview>

## Errors [#errors]

When the function rejects (or the save throws), the button stops being busy, a polite status region announces "medical-certificate.pdf couldn't be downloaded" (`translations.error`), and `onError` receives the error. Nothing is saved, and `onDone` doesn't fire. The message is cleared on the next click.

Success is silent: the browser's own download bar or panel is the feedback, and an extra announcement would talk over it.

<Preview code="&#x22;<DownloadButton\n  name=\&#x22;medical-certificate.pdf\&#x22;\n  data={fetchCertificate}\n  onError={(error) => setError(error.message)}\n  color=\&#x22;red\&#x22;\n  variant=\&#x22;light\&#x22;\n>\n  Download certificate\n</DownloadButton>&#x22;">
  <DownloadButtonErrorDemo />
</Preview>

If `onError` shows a toast that announces itself, the failure is heard twice. Pass `translations={{ error: () => '' }}` to leave it to the toast.

## Internationalization [#internationalization]

Every string the button shows or announces is in `translations`. An icon-only button's name is your own `aria-label`.

| Key       | Default                                                                       |
| --------- | ----------------------------------------------------------------------------- |
| `label`   | `"Download"`                                                                  |
| `loading` | `"Preparing download…"`                                                       |
| `error`   | ``(name) => name ? `${name} couldn't be downloaded` : "The download failed"`` |

<Preview code="&#x22;<DownloadButton\n  name=\&#x22;notes.csv\&#x22;\n  data={fetchNotes}\n  translations={{\n    label: 'Télécharger',\n    loading: 'Préparation du téléchargement…',\n    error: (name) => (name ? `Échec du téléchargement de ${name}` : 'Échec du téléchargement'),\n  }}\n/>&#x22;">
  <DownloadButtonFrenchDemo />
</Preview>

The button is a `Button`, laid out with logical properties: on a right-to-left page the icon moves to the right. The download icon points down, so it isn't mirrored.

## Accessibility [#accessibility]

* **A real button.** It's a `<button type="button">` (or your element, under `asChild`), named by its children or its `aria-label`. `Enter` and `Space` start the download, like a click.
* **Busy, not disabled.** While loading it keeps focus and stays in the tab order, with `aria-busy="true"` and "Preparing download…" added to its name. Button's own `loading` sets `disabled`, which would drop focus to the page, so DownloadButton doesn't use it.
* **One announcement, on failure.** A `role="status"` region beside the button speaks only when the download fails. It's visually hidden with `position: fixed`, so it can't stretch a scrolling container.
* **Disabled** disables the button; under `asChild` the child gets `disabled` and `aria-disabled`, and a click saves nothing.

## Slow downloads and Safari [#slow-downloads-and-safari]

A save that follows a long `await` is no longer part of the click: the page's *transient user activation*, which lets a script do what only a click may, lapses a few seconds after it (five in Chrome; WebKit had dropped it by six in our run). Browsers block a popup opened that late. A download through a link with a `download` attribute, which is how `DownloadButton` saves, isn't gated on activation.

We checked it in Chromium and WebKit, the engine behind Safari, through Playwright. A Blob saved six seconds after the click, when `navigator.userActivation.isActive` had already turned `false`, still downloaded in both, with the right name and bytes. So did the demos above: a Blob, a promise after 2.5 seconds, and a same-origin URL. A cross-origin URL returned after 2.5 seconds downloaded too, named by its `Content-Disposition`, and the page stayed put.

What headless WebKit can't show is the Safari app's own "Do you want to allow downloads on this site?" prompt, which it asks once per site. If a user declines it, nothing is saved and nothing fails in the page, so `onDone` still fires.

## saveFile [#savefile]

The function underneath, exported from the package root for code that isn't a button: a menu item, a keyboard shortcut, the end of a form submission. See [File helpers](/docs/utilities/files#savefile).

```tsx
import { saveFile } from '@42-central/ui-react';

saveFile(blob, 'grades.csv');
```

## API [#api]

<TypeTable
  type="{
  data: {
    type: 'Blob | string | (({ signal }) => Blob | string | Promise<Blob | string>)',
    description: 'The file: a Blob, a URL, or a function resolving one on click. signal aborts when the button unmounts first.',
    required: true,
  },
  name: {
    type: 'string',
    description: &#x22;The file name. A File's own name, or a URL's last segment, by default. Ignored by browsers for a cross-origin URL.&#x22;,
  },
  type: { type: 'string', description: 'The MIME type to save a Blob with, when it has none.' },
  onError: { type: '(error: unknown) => void', description: 'Fires when data rejects or the save throws.' },
  onDone: { type: '() => void', description: 'Fires once the file has been handed to the browser.' },
  translations: {
    type: '{ label?, loading?, error? }',
    description: 'The default label, the loading text added to the name, and the failure announcement.',
  },
  icons: { type: '{ download? }', description: 'The leading icon. null renders none. Not used under asChild.' },
  asChild: {
    type: 'boolean',
    default: 'false',
    description: &#x22;Makes the single child the button. Only behaviour is merged onto it, not Button's styling.&#x22;,
  },
  disabled: { type: 'boolean', default: 'false', description: 'Disables the button; a click saves nothing.' },
  variant: { type: '&#x22;filled&#x22; | &#x22;light&#x22; | &#x22;outline&#x22; | &#x22;subtle&#x22;', default: '&#x22;filled&#x22;', description: 'Button variant. Ignored under asChild.' },
  color: { type: 'Color', description: 'Button palette. Ignored under asChild.' },
  size: { type: '&#x22;xs&#x22; | &#x22;sm&#x22; | &#x22;md&#x22; | &#x22;lg&#x22; | &#x22;xl&#x22;', default: '&#x22;md&#x22;', description: 'Button size. Ignored under asChild.' },
  testId: { type: 'string', description: 'Renders as data-testid on the button. See [Testing](/docs/testing).' },
}"
/>

A caller's `onClick` runs first: call `event.preventDefault()` in it to stop the save (a confirmation step). `endSlot` and the other `Button` props pass through; `loading` and `startSlot` don't exist here, since the button manages its own busy state and icon.
