# File helpers (/docs/utilities/files)



Plain functions behind [`FileItem`](/docs/file-item), [`FileUpload`](/docs/file-upload), [`DownloadButton`](/docs/download-button) and [`FilePreview`](/docs/file-preview), exported from the package root for your own table cells, captions, messages and menu items. They take no React, so they work in a loader or a test as well. One hook joins them, [`useObjectUrl`](#useobjecturl): the URL for a Blob in your own `<img>`.

```tsx
import { fileKind, formatFileSize, openFile, saveFile, useObjectUrl, viewableType } from '@42-central/ui-react';
```

## formatFileSize [#formatfilesize]

A byte count in decimal units (1 MB is 1,000,000 bytes, as operating systems show it), to three significant digits, with the locale's own unit names and separators.

```tsx
formatFileSize(48_213); // "48.2 kB"
formatFileSize(48_213, 'fr-FR'); // "48,2 ko"
formatFileSize(1_234_567, 'fr-FR'); // "1,23 Mo"
formatFileSize(5 * 1024 * 1024); // "5.24 MB"
```

The locale defaults to `DEFAULT_LOCALE` (`"en-US"`), never the runtime's, so a server render and the browser can't disagree. In a component, pass [`useLocale()`](/docs/hooks/use-locale) to follow the [`IntlProvider`](/docs/intl):

```tsx
const locale = useLocale();

<td>{formatFileSize(document.size, locale)}</td>
```

That is the kit's one pattern for `Intl` formatting: the hook resolves the locale, and the formatting stays a plain function you can call anywhere. There is no `useFormatFileSize`.

<TypeTable
  type="{
  bytes: { type: 'number', description: 'The size in bytes.', required: true },
  locale: { type: 'string', default: '&#x22;en-US&#x22;', description: 'A BCP-47 tag. Pass useLocale() inside a component.' },
}"
/>

Returns a `string`.

## fileKind [#filekind]

The kind of a file, from its MIME type, or from its name's extension when the type is empty or generic: browsers often report `""` for a `.csv` or a `.docx`, and servers send `application/octet-stream`. One of `FILE_KINDS`: `image`, `video`, `audio`, `pdf`, `text`, `archive`, `spreadsheet`, `document`, `code`, `font` or `other`.

```tsx
fileKind('application/pdf'); // "pdf"
fileKind('text/csv'); // "spreadsheet", not "text": an exact type wins over its family
fileKind('', 'grades.csv'); // "spreadsheet"
fileKind('application/octet-stream', 'backup.tar.gz'); // "archive"
fileKind(file.type, file.name); // a picked File
```

One lookup decides, trying an exact MIME type, then its family (`image/*`), then the extension. `FileItem` keys its `icons` by these kinds.

<TypeTable
  type="{
  type: { type: 'string', default: '&#x22;&#x22;', description: 'The MIME type. Parameters (; charset=…) and case are ignored.' },
  name: { type: 'string', default: '&#x22;&#x22;', description: 'The file name, for its extension.' },
}"
/>

Returns a `FileKind`. `extensionOf(name)` is the extension it reads: `".pdf"` for `"Report.FINAL.PDF"`, `""` without one.

## saveFile [#savefile]

Saves a `Blob`, a `File` or a URL as a file, through a hidden link with a `download` attribute. It's what [`DownloadButton`](/docs/download-button) calls; reach for it directly when the download doesn't start from a button (a menu item, a shortcut, the end of a form submission). It makes no request: fetch the file first, and pass the Blob.

```tsx
saveFile(new Blob([csv], { type: 'text/csv' }), 'grades.csv');
saveFile(file); // a File keeps its own name
saveFile('/exports/grades.csv', 'Q1.csv'); // a same-origin URL, renamed
saveFile(presignedUrl); // a cross-origin URL: named by the server
```

* **A Blob or a File** is saved through an object URL. The name defaults to the File's own, then to `"download"`. `type` retypes a Blob without one (`new Blob([csv])` has none), without copying it.
* **A same-origin URL**, or a `blob:` or `data:` one, is downloaded under `name`, which defaults to its last path segment.
* **A cross-origin URL** is followed like a link. Browsers ignore the file name on it, so the server's `Content-Disposition` names the file, and without `attachment` the browser shows the file rather than saving it. See [Filenames from presigned URLs](/docs/download-button#a-presigned-url).
* **On the server** it does nothing, so shared code can call it during a render or in a loader.

<Callout type="info" title="Why the object URL lives for 40 seconds">
  Revoking an object URL right after the click has cancelled the download in Safari ([WebKit bug 185531](https://bugs.webkit.org/show_bug.cgi?id=185531), and again on iOS in [212279](https://bugs.webkit.org/show_bug.cgi?id=212279)): the browser reads the URL after `click()` returns, not during it. A zero-millisecond timer only moves the race one task later. `saveFile` revokes it `SAVE_FILE_REVOKE_DELAY` (40 s) later, the delay [FileSaver.js](https://github.com/eligrey/FileSaver.js) uses for the same reason. The Blob stays in memory that long, which the download needs anyway.
</Callout>

<TypeTable
  type="{
  data: { type: 'Blob | string', description: 'A Blob or File, or a URL (relative URLs resolve against the page).', required: true },
  name: { type: 'string', description: &#x22;The file name. A File's own name, a same-origin URL's last segment, or \&#x22;download\&#x22; by default.&#x22; },
  'options.type': { type: 'string', description: 'The MIME type to save a Blob with. Ignored for a URL.' },
}"
/>

Returns nothing.

## openFile [#openfile]

Opens a Blob, a URL, or what your function resolves in a new tab: the "Open in new tab" behind [`FilePreview.Open`](/docs/file-preview#openfile). Call it in a click handler.

```tsx
openFile(file); // a picked File
openFile(presignedUrl, { name: 'consent.pdf' });
openFile(({ signal }) => api.blob(`/documents/${id}`, { signal }), { name: 'contract.pdf' });
```

* **Popup-safe.** The tab opens synchronously in the click, before your function is called, then shows the file when the promise resolves. It closes again if the promise rejects or `signal` aborts, and the returned promise rejects.
* **A blocked popup saves the file** with `saveFile`, and resolves `"saved"` instead of `"opened"`.
* **Only allowlisted files are shown** (`viewableType`, below). Anything else is saved, never navigated to: an uploaded HTML or SVG would run as your app. A cross-origin URL is always followed (its script runs with its own origin); a same-origin one only when its type or name is viewable; a `blob:` or `data:` string never.
* **The tab can't reach back**: its `opener` is cut before anything loads.
* **The object URL lives while the tab shows it**, checked every `OPEN_FILE_POLL` (2 s), and is revoked once the tab closes or navigates away, or after `OPEN_FILE_MAX_AGE` (one hour). Saving from the browser's PDF viewer and reloading keep working meanwhile.

The tab's title is the PDF's own Title metadata, or the object URL's id without it: set the title where the PDF is generated. See [The tab's title](/docs/file-preview#openfile).

<TypeTable
  type="{
  source: {
    type: 'Blob | string | (({ signal }) => Blob | string | Promise<Blob | string>)',
    description: 'The file, a URL, or a function resolving one, called inside the click.',
    required: true,
  },
  'options.name': { type: 'string', description: &#x22;The tab's title while it loads, the saved file's name, and with type, whether it may be shown. A File's own by default.&#x22; },
  'options.type': { type: 'string', description: &#x22;The MIME type, when the Blob's own is missing, or for a URL.&#x22; },
  'options.signal': { type: 'AbortSignal', description: 'Aborts a pending function: the tab closes and the promise rejects.' },
}"
/>

Returns a `Promise<"opened" | "saved">`.

## viewableType [#viewabletype]

The type a browser may render a file under, or `undefined` when it must only be saved. The one allowlist `FilePreview`, `openFile` and [`useObjectUrl`](#useobjecturl) share: always one of a fixed set, never the file's own type passed through, so re-wrap the Blob under it before making an object URL (`useObjectUrl` does it for you).

```tsx
viewableType('application/pdf', 'contract.pdf'); // "application/pdf"
viewableType('', 'scan.JPG'); // "image/jpeg"
viewableType('text/csv', 'grades.csv'); // "text/plain;charset=utf-8"
viewableType('text/html', 'contract.pdf'); // undefined: the type says HTML
viewableType('image/svg+xml', 'logo.svg'); // undefined: SVG runs script

const safe = viewableType(file.type, file.name);
if (safe) url = URL.createObjectURL(file.slice(0, file.size, safe));
```

The set: `application/pdf`; `image/png`, `jpeg`, `gif`, `webp`, `avif`, `bmp`; `video/mp4`, `webm`, `ogg`, `quicktime`; `audio/mpeg`, `mp4`, `aac`, `wav`, `ogg`, `webm`, `flac`; and plain text (text, Markdown, CSV, TSV, JSON) as `text/plain;charset=utf-8`. The kind is `fileKind`'s, so a specific type wins over the name. Why these and nothing else is measured in [FilePreview's Security section](/docs/file-preview#security).

<TypeTable
  type="{
  type: { type: 'string', default: '&#x22;&#x22;', description: 'The MIME type.' },
  name: { type: 'string', default: '&#x22;&#x22;', description: 'The file name, for a missing or generic type.' },
}"
/>

Returns a `string` or `undefined`.

## useObjectUrl [#useobjecturl]

A URL for a `Blob` or a `File` that's safe to put in your page: in an `<img>`, a `<video>`, a link. The one mechanism behind every kit surface that shows a Blob: [`FileItem`](/docs/file-item) and [`FileUpload`](/docs/file-upload) thumbnails, [`FilePreview`](/docs/file-preview), [`ImageCropper`](/docs/image-cropper) and [`PhotoCapture`](/docs/photo-capture).

```tsx
const url = useObjectUrl(file);

<img src={url} alt="" />
```

Never `URL.createObjectURL(file)` for an uploaded file. An object URL has your app's origin: the `<img>` won't run an SVG's script, but "Open image in new tab", dragging the image to the tab bar or copying its address navigates to the URL, and an `.svg` or `.html` there runs as your app, with its storage and its API. What `useObjectUrl` hands out instead:

| The Blob                                                                                           | The URL                                                                                                                                                          |
| -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| On `viewableType`'s list: PDF, PNG, JPEG, GIF, WebP, AVIF, BMP, common video and audio, plain text | An object URL for the Blob re-wrapped under that type, never the type it claims. Revoked when the Blob changes or the component unmounts.                        |
| SVG, by type, or by name for a missing or generic type                                             | A `data:` URL. Its document has an opaque origin, so its script can't reach your app even in a tab of its own. Up to `SVG_DATA_URL_LIMIT` (5 MB); past it, none. |
| Anything else: HTML, XML, an unknown or "binary" type                                              | `undefined`. Show an icon, or offer a download with [`saveFile`](#savefile).                                                                                     |
| A string                                                                                           | Passed through: your URL, under your server's `Content-Type`.                                                                                                    |

**Why 5 MB for an SVG.** A `data:` URL lives as a string, a third larger than the file in base64, plus the `<img>`'s copy, for every mounted thumbnail. An SVG past 5 MB is a map or an export, not a logo, and a list of them would hold that many times over. FileItem shows its kind icon then, and FilePreview its download panel.

**A Blob with no type**, such as `new Blob([bytes])`, is shown only by its name: a `File`'s own, or `options.name`. Pass `options.type` when you know better than the Blob.

It keeps the guarantees of a hand-rolled one: the URL is made in an effect, so it's `undefined` on the server and for the first render (an SVG's until it's read), Strict Mode's double render leaks nothing, and a render after the Blob changes never hands out the previous, already revoked URL.

<TypeTable
  type="{
  source: { type: 'Blob | string | null | undefined', description: 'A Blob or File to show, or a URL to pass through.', required: true },
  'options.name': { type: 'string', description: &#x22;The file name, for a missing or generic type. A File's own by default.&#x22; },
  'options.type': { type: 'string', description: &#x22;The MIME type, in place of the Blob's own.&#x22; },
}"
/>

Returns a `string`, or `undefined` while the URL is made, and for a Blob it won't show. A live demo is on the [useObjectUrl](/docs/hooks/use-object-url) hook page.
