# FilePreview (/docs/file-preview)





`FilePreview` shows one file: a PDF in the browser's built-in PDF viewer, an image, a video or a sound with native controls, a text file as text, and anything else as a panel with a download button. It's the body you put in a [`Modal`](/docs/modal), a [`Drawer`](/docs/drawer) or a page. There is no PDF library: the browser renders the file itself.

The kit makes no request. Give it the file as a `File` or `Blob`, as a URL the browser loads itself, or as a function of yours that resolves either one.

```tsx
import { FilePreview } from '@42-central/ui-react/file-preview';

<FilePreview file={pickedFile} />
<FilePreview src={document.url} name={document.name} />
<FilePreview
  name="contract.pdf"
  data={({ signal }) => api.get(`/documents/${id}`, { signal }).then((r) => r.blob())}
/>
```

## Playground [#playground]

<story.Playground />

## A PDF [#a-pdf]

A PDF loads in the browser's own viewer, through an `<object type="application/pdf">`: pages, zoom, search, print and save come with it. The header shows the name, the extension and size, an **Open in new tab** button and a **Download** button. The root has a height of its own (`min(75dvh, 48rem)`), so a PDF has room on a page and in a dialog without any sizing; override it with `className` (`h-96`, or `h-full` in a parent with a definite height).

<Preview align="block" code="`<FilePreview src=&#x22;/files/internship-agreement.pdf&#x22; name=&#x22;internship-agreement.pdf&#x22; />`">
  <FilePreviewPdfDemo />
</Preview>

<Callout type="info" title="Why an object, not an iframe">
  Both get the same viewer in Chromium, Firefox and Safari. The difference is the keyboard inside a [`Modal`](/docs/modal) or a [`Drawer`](/docs/drawer): their focus trap looks inside a same-origin frame for tab stops, finds Chrome's viewer document empty, and leaves the frame out, so `Tab` cycled through the dialog's buttons and never reached the PDF (measured in Chromium). It counts an `<object>` as one stop, and `End` then scrolls the PDF to its last page. The `type` attribute is no safety net (Chromium rendered an HTML resource behind `type="application/pdf"`), which is why only a re-typed PDF is ever embedded; see [Security](#security).
</Callout>

## Every kind of file [#every-kind-of-file]

The renderer follows the file's kind ([`fileKind`](/docs/utilities/files#filekind), from its type, then its extension) and the [allowlist](#security) below. Switch the file:

<Preview align="block" code="&#x22;<FilePreview\n  name=\&#x22;campus.jpg\&#x22;\n  data={({ signal }) => fetch('/files/campus.jpg', { signal }).then((r) => r.blob())}\n/>\n\n<FilePreview file={new File([html], 'cover-letter.html', { type: 'text/html' })} />&#x22;">
  <FilePreviewKindsDemo />
</Preview>

| The file                                                    | Shown as                                                                                                            |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| PDF                                                         | The browser's PDF viewer, in an `<object>` named "Preview of internship-agreement.pdf" (`translations.label`).      |
| PNG, JPEG, GIF, WebP, AVIF, BMP                             | The kit [`Image`](/docs/image), contained in the box.                                                               |
| SVG                                                         | An `<img>`, from a `data:` URL (see [Security](#security)).                                                         |
| MP4, WebM, Ogg, QuickTime; MP3, AAC, WAV, Ogg, FLAC         | `<video>` or `<audio>` with the browser's controls.                                                                 |
| Text, CSV, TSV, JSON, code, Markdown, logs                  | Its characters, in a scrolling `<pre>`. Only from a `File` or `Blob`, which can be read; see below.                 |
| Anything else, or a PDF where the browser has no PDF viewer | The panel: the kind icon, the name, the extension and size, "No preview for this file type", and a download button. |

**Text** is read from the Blob and shown as characters, never parsed: the HTML file above shows its source, and its `<script>` is text. A file longer than `limit` (500 kB by default, `FILE_PREVIEW_TEXT_LIMIT`) is cut there, with "Showing the first 500 kB of 1.2 MB" above it. It's decoded as UTF-8; a character cut in half at the limit is dropped rather than shown as `�`. A text **URL** gets the panel instead: reading it would mean fetching it, and the kit doesn't. Return a Blob from `data` to preview it.

## Your own fetch [#your-own-fetch]

A URL in a link can't carry a bearer token. Pass `data` instead: a function that receives an `AbortSignal` and returns a Blob or a URL (a presigned link), or a promise of one. It runs when the preview mounts; while it's pending, the content shows a spinner named "Loading internship-agreement.pdf…" and is `aria-busy`. Give `name` (and `type` when the name has no extension) so the header and the renderer are right before the file arrives.

<Preview align="block" code="&#x22;<FilePreview\n  name=\&#x22;internship-agreement.pdf\&#x22;\n  data={async ({ signal }) => {\n    const response = await fetch(`/api/documents/${id}`, {\n      headers: { Authorization: `Bearer ${token}` },\n      signal,\n    });\n    if (!response.ok) throw new Error(response.statusText);\n    return response.blob();\n  }}\n/>&#x22;">
  <FilePreviewLoadingDemo />
</Preview>

When the preview unmounts first (the dialog closes), `signal` aborts and a late result is ignored; pass it on to `fetch` so the request stops too. `data` runs once per mount: to show another file, give the preview a `key`.

The header's buttons work while the file is still loading. **Download** waits for the same promise, without a second request. **Open in new tab** opens the tab inside the click, as browsers require, and shows the file once it arrives.

## Errors and Retry [#errors-and-retry]

When `data` rejects (or throws), the content shows "medical-certificate.pdf couldn't be loaded" with a **Retry** button, and a polite status region announces it. Retry calls `data` again; focus moves to the content area, so it isn't dropped with the button. This demo fails once, then succeeds.

<Preview align="block" code="`<FilePreview name=&#x22;medical-certificate.pdf&#x22; data={fetchCertificate} />`">
  <FilePreviewErrorDemo />
</Preview>

## In a Modal or a Drawer [#in-a-modal-or-a-drawer]

The usual place for a preview: opened from a [`FileItem`](/docs/file-item) row's `actions`, in a `Modal` on a desktop and a bottom `Drawer` on a phone. The overlay's title names the file, so the preview drops its own name and keeps the meta and the actions. Narrow the window below 40rem to get the drawer.

<Preview align="block" code="&#x22;const phone = useMediaQuery('(width < 40rem)');\nconst [open, setOpen] = useState<Document | null>(null);\n\nconst preview = (className?: string) => open && (\n  <FilePreview.Root\n    className={className}\n    name={open.name}\n    type={open.type}\n    size={open.size}\n    data={({ signal }) => fetchDocument(open.id, signal)}\n  >\n    <FilePreview.Header>\n      <FilePreview.Meta className=\&#x22;flex-1\&#x22; />\n      <FilePreview.Actions>\n        <FilePreview.Open />\n        <FilePreview.Download />\n      </FilePreview.Actions>\n    </FilePreview.Header>\n    <FilePreview.Content />\n  </FilePreview.Root>\n);\n\n<FileItem\n  file={document}\n  actions={\n    <ActionIcon variant=\&#x22;subtle\&#x22; color=\&#x22;neutral\&#x22; size=\&#x22;xs\&#x22; aria-label={`View ${document.name}`}\n      aria-haspopup=\&#x22;dialog\&#x22; onClick={() => setOpen(document)}>\n      <Eye className={iconStroke} aria-hidden />\n    </ActionIcon>\n  }\n/>\n\n{phone ? (\n  <Drawer open={open !== null} onOpenChange={(next) => !next && setOpen(null)} placement=\&#x22;bottom\&#x22;\n    title={open?.name} withGrabber>\n    {preview('h-[60dvh]')}\n  </Drawer>\n) : (\n  <Modal open={open !== null} onOpenChange={(next) => !next && setOpen(null)} title={open?.name} size=\&#x22;xl\&#x22;>\n    {preview()}\n  </Modal>\n)}&#x22;">
  <FilePreviewOverlayDemo />
</Preview>

Focus moves into the dialog and is trapped there, as with any `Modal`. The PDF frame, the text region and the media controls come in the tab order after the header's buttons.

## Parts [#parts]

`<FilePreview>` is a ready-made arrangement. `withHeader={false}` drops the header, `meta` replaces the extension and size, and `actions` adds your buttons before Open and Download. For your own layout:

| Part                   | Renders                                             | Notes                                                                                                       |
| ---------------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `FilePreview.Root`     | A `<div>`, a flex column                            | The file (`file`, `src` or `data`), `name`, `type`, `size`, `limit`, `translations`, `icons`. Loads `data`. |
| `FilePreview.Header`   | The bar above the file                              | A size container: below 28rem the action labels fold into their icons.                                      |
| `FilePreview.Name`     | The name, truncated, with a `title`                 | `asChild` makes it your heading.                                                                            |
| `FilePreview.Meta`     | "PDF · 4.98 kB"                                     | `children` replace it.                                                                                      |
| `FilePreview.Actions`  | A row of buttons                                    |                                                                                                             |
| `FilePreview.Open`     | A `Button`, through `openFile`                      | Renders only for a file a tab may show. Prominent on a touch screen.                                        |
| `FilePreview.Download` | A [`DownloadButton`](/docs/download-button)         | Saves the file at hand, or waits for `data`.                                                                |
| `FilePreview.Content`  | The file, or its loading, error or no-preview state | Fills the rest of the root; the file scrolls inside it.                                                     |

## openFile [#openfile]

"Open in a new tab" on its own, for a row action or a link-like button: `openFile(source, { name, type, signal })`. The source is a Blob, a URL, or a function resolving one. Call it in a click handler; it resolves `"opened"`, or `"saved"` when it saved the file instead.

<Preview code="&#x22;<Button onClick={() => openFile(notes)}>Open the notes</Button>\n\n<Button onClick={() => openFile(({ signal }) => fetchAgreement(signal), { name: 'internship-agreement.pdf' })}>\n  Open the agreement\n</Button>&#x22;">
  <FilePreviewOpenFileDemo />
</Preview>

* **The tab opens inside the click.** Browsers block a popup opened after an `await`. With a function, the tab opens first (blank, titled with `name`), then shows the file when the promise resolves, and closes if it rejects or `signal` aborts.
* **A blocked popup saves the file.** When the browser blocks the tab, `openFile` calls [`saveFile`](/docs/utilities/files#savefile) and resolves `"saved"`.
* **Only allowlisted files are shown.** Anything else is saved, never navigated to (see [Security](#security)). That includes a file a function resolves: the blank tab closes, and the file downloads.
* **The tab can't reach back.** Its `opener` is cut before anything loads. (`window.open`'s `noopener` would return no window to point at the file.)
* **The object URL lives while the tab shows it.** The 42-frontend helper this replaces revoked it after 60 seconds, after which saving from Chrome's PDF viewer or reloading the tab failed. `openFile` checks the tab every 2 seconds (`OPEN_FILE_POLL`) and revokes the URL once the tab is closed or has navigated elsewhere, and after an hour (`OPEN_FILE_MAX_AGE`) at the latest, so a tab left open all day doesn't pin the Blob in memory forever. A background tab's timers are throttled to once a minute in Chrome, which only delays the revoke. Closing or reloading your app revokes every object URL it made, whatever the timer says.

<Callout type="info" title="The tab's title">
  A tab showing a Blob is titled by the PDF's own **Title** metadata, and by the object URL's id when the PDF has none: in Chromium, our sample PDF's tab reads "Internship agreement - sample", the same file without the metadata reads `e14db6a9-cf59-…`. The fix belongs where the PDF is made: have your generator set the document title. We tried hosting the PDF in a titled blank page of our own instead; the title was right, but reloading that tab shows an empty page, and iOS shows only the first page of a PDF in a frame, which defeats the point of opening it. So `openFile` doesn't.
</Callout>

## Security [#security]

A Blob's object URL has your app's origin. If an uploaded `.html` or `.svg` were loaded from one, in a frame or in a tab, its script would run as your app, with your cookies' reach and your API: stored XSS in an admin tool. We checked which types do this in Chromium and WebKit (the engine behind Safari), with a script that writes to the app's `localStorage`:

| Content          | Typed as                                                                              | Chromium  | WebKit                     |
| ---------------- | ------------------------------------------------------------------------------------- | --------- | -------------------------- |
| HTML             | `text/html`                                                                           | **runs**  | **runs**                   |
| HTML             | `application/octet-stream`, `application/zip`, or no type                             | downloads | **runs** (sniffed as HTML) |
| SVG markup       | `image/svg+xml`, `application/xml`, `text/xml`                                        | **runs**  | **runs**                   |
| HTML or SVG      | `application/pdf`, `text/plain`, `image/png`, `image/jpeg`, `video/mp4`, `audio/mpeg` | inert     | inert                      |
| HTML             | `text/html`, behind `<object type="application/pdf">`                                 | **runs**  | inert                      |
| SVG markup       | an `<img>` from an object URL, then "Open image in new tab"                           | **runs**  | **runs**                   |
| SVG markup       | an `<img>` from a `data:` URL, then opened in a tab                                   | inert     | inert                      |
| Any of the above | saved through a `download` link                                                       | inert     | inert                      |

So re-typing an unknown file as "binary" isn't a defence (WebKit sniffs it), and neither is `<object type>` (Chromium ignores it). What FilePreview and `openFile` do instead:

1. **An allowlist of types, not of files.** [`viewableType(type, name)`](/docs/utilities/files#viewabletype) maps a file to one of a fixed set: `application/pdf`, a raster image type, a common video or audio type, or `text/plain`. Never the file's own type passed through. A Blob is re-wrapped under it (`blob.slice(0, size, type)`) before it gets a URL, so HTML that calls itself `contract.pdf` with no type is rendered as a PDF, which fails to load and runs nothing. A specific type wins over a reassuring name: HTML typed `text/html` but named `contract.pdf` is not framed.
2. **Only PDFs are embedded.** Not in a `sandbox`ed frame, which would be the textbook fix: Chrome refuses to run its PDF viewer in one (it shows an error page, measured), so the protection is that nothing but a re-typed PDF ever reaches the viewer.
3. **Text is a text node.** Never `innerHTML`, so markup stays characters.
4. **SVG is an `<img>`, from a `data:` URL.** An `<img>` never runs an SVG's script, but "Open image in new tab" on an object URL would, as the app. A `data:` URL's document has an opaque origin, so even then the script can't touch the app.
5. **Everything else is saved, never navigated to.** The panel's button and `openFile` save it through a `download` link.

Rules 1 and 4 aren't FilePreview's own: they are [`useObjectUrl`](/docs/utilities/files#useobjecturl), the one way the kit turns a Blob into a URL, so [`FileItem`](/docs/file-item) and [`FileUpload`](/docs/file-upload) thumbnails, [`ImageCropper`](/docs/image-cropper) and [`PhotoCapture`](/docs/photo-capture) follow them too. Before it, their thumbnails used the file's own type, and an uploaded SVG's "Open image in new tab" ran as the app. The table above is re-measured by `pnpm run security:files`, a Playwright harness in `packages/react/scripts/security/` that pushes hostile HTML and SVG through every one of these surfaces in Chromium and WebKit and fails on any script that runs with the app's origin.

What the kit can't check is a **URL**: the browser follows the server's `Content-Type`. A cross-origin URL (a presigned S3 link) is safe to frame or open, since its script runs with that origin and the tab has no `opener`. A same-origin URL is framed or opened only when its `type` or name is viewable, but then the server decides. Serve uploads from a separate origin when you can; otherwise send the real `Content-Type`, `X-Content-Type-Options: nosniff` and `Content-Disposition: attachment` for anything not on the list. `openFile` never opens a `blob:` or `data:` string, whose real type it can't check: pass the Blob.

A PDF can carry JavaScript of its own. Chrome's and Firefox's viewers run it in their own sandbox, not with your origin, and the allowlist doesn't change that.

## Phones and tablets [#phones-and-tablets]

* **iOS shows only the first page of a PDF inline.** Safari on iPhone and iPad draws a framed PDF as a still image of its first page, with no scrolling. On a touch screen (`pointer: coarse`), FilePreview adds "Only the first page may show here." above the PDF with its own **Open in new tab** button, and the header's Open button turns prominent. In a tab, iOS shows the whole document in its viewer.
* **Android has no inline PDF viewer.** Chrome on Android reports `navigator.pdfViewerEnabled === false`, so FilePreview shows the panel ("This browser can't show PDFs here") with Download and Open, which hands the PDF to the system's viewer.
* **What we could check.** Playwright's WebKit doesn't render PDFs at all, so the iOS behaviour above comes from Safari itself, not from our automation. In WebKit we checked the security table, the panel, the image and text renderers and `openFile`'s tab; in Chromium, the PDF viewer too.

## Documents in a Lightbox [#documents-in-a-lightbox]

Not yet. The [open-index seam](/docs/gallery#opening-a-photo) is how it would come: a list of document tiles under an `OpenIndexProvider`, and a viewer that renders a `FilePreview` for the opened index, the way a [`Lightbox.Slide`](/docs/lightbox) takes custom media.

## Internationalization [#internationalization]

Every string is in `translations`. The download button's own strings sit under `download`. Sizes follow the [`IntlProvider`](/docs/intl) locale.

| Key           | Default                                                                                           |
| ------------- | ------------------------------------------------------------------------------------------------- |
| `label`       | ``(name) => `Preview of ${name}` `` (the frame's title, the media's and the text region's names)  |
| `loading`     | ``(name) => `Loading ${name}…` ``                                                                 |
| `error`       | ``(name) => `${name} couldn't be loaded` ``                                                       |
| `retry`       | `"Retry"`                                                                                         |
| `unsupported` | `"No preview for this file type"`                                                                 |
| `viewer`      | `"This browser can't show PDFs here"`                                                             |
| `truncated`   | ``(shown, total) => `Showing the first ${shown} of ${total}` ``                                   |
| `pages`       | `"Only the first page may show here."`                                                            |
| `open`        | `"Open in new tab"`                                                                               |
| `openError`   | ``(name) => `${name} couldn't be opened` ``                                                       |
| `download`    | `{ label, loading, error }`, as on [`DownloadButton`](/docs/download-button#internationalization) |

<Preview align="block" code="&#x22;<IntlProvider locale=\&#x22;fr-FR\&#x22;>\n<FilePreview\n  file={cv}\n  translations={{\n    label: (name) => `Aperçu de ${name}`,\n    loading: (name) => `Chargement de ${name}…`,\n    error: (name) => `Impossible de charger ${name}`,\n    retry: 'Réessayer',\n    unsupported: 'Aucun aperçu pour ce type de fichier',\n    viewer: 'Ce navigateur ne peut pas afficher les PDF ici',\n    truncated: (shown, total) => `Affichage des ${shown} premiers sur ${total}`,\n    pages: 'Seule la première page peut s’afficher ici.',\n    open: 'Ouvrir dans un nouvel onglet',\n    openError: (name) => `Impossible d’ouvrir ${name}`,\n    download: { label: 'Télécharger' },\n  }}\n/>\n</IntlProvider>&#x22;">
  <FilePreviewFrenchDemo />
</Preview>

On a right-to-left page the header mirrors (logical properties throughout), and text files set `dir="auto"`, so an Arabic or Hebrew file reads from its own side. The PDF viewer and the media controls are the browser's, in the browser's language.

## Accessibility [#accessibility]

* **A named, reachable PDF.** The PDF's `<object>` has an `aria-label` ("Preview of contract.pdf", from `translations.label`) and is a tab stop; the video and audio elements are named the same way. Once focus is inside, the browser's viewer owns the keys (arrows and `End` scroll the pages); `Shift+Tab` comes back out to the header. Focused, it shows the kit's ring, drawn on an overlay after it ([`peer-focus-visible`](/docs/focus#focus-on-a-scroll-region)): its own ring would paint under the viewer.
* **A reachable text region.** Text sits in a [`ScrollArea`](/docs/scroll-area) named the same way, a region that joins the tab order while it overflows, so a keyboard user can scroll it with the arrow keys. Its ring is the kit's, inside its edge.
* **Real buttons.** Open, Download and Retry are buttons named by their text; in a narrow header the text is visually hidden but stays the name.
* **Loading and errors.** The spinner is named "Loading contract.pdf…" and the content is `aria-busy`. A failure is announced once, through a polite status region, and focus moves to the content on Retry.
* **Captions** are the file's own: the kit has no track to add to a video.

## API [#api]

<TypeTable
  type="{
  file: { type: 'Blob', description: 'A picked File, or a Blob (then give it a name). One of file, src or data.' },
  src: { type: 'string', description: 'A URL the browser loads itself. Needs name.' },
  data: {
    type: '({ signal }) => Blob | string | Promise<Blob | string>',
    description: 'Your function resolving the file, run on mount and on Retry. signal aborts on unmount and on the next attempt. Needs name.',
  },
  name: { type: 'string', description: &#x22;The file name: the title, and with type, how it is shown. A File's own by default.&#x22; },
  type: { type: 'string', description: &#x22;The MIME type, when the file's own is missing or generic.&#x22; },
  size: { type: 'number', description: &#x22;In bytes, for the meta line. A Blob's own by default.&#x22; },
  limit: { type: 'number', default: '500_000', description: 'How many bytes of a text file to show.' },
  withHeader: { type: 'boolean', default: 'true', description: 'Renders the header: name, meta, Open and Download.' },
  meta: { type: 'ReactNode', description: 'Replaces the extension and size on the meta line.' },
  actions: { type: 'ReactNode', description: 'Your buttons, before Open and Download.' },
  translations: { type: 'FilePreviewTranslations', description: 'See Internationalization.' },
  icons: {
    type: 'IconMap<FileKind | &#x22;open&#x22; | &#x22;download&#x22; | &#x22;retry&#x22; | &#x22;error&#x22;>',
    description: &#x22;The panel's kind icons, and the buttons' and error state's icons.&#x22;,
  },
  classNames: { type: '{ root?, header?, name?, meta?, actions?, content? }', description: 'Per-part classes.' },
  testId: { type: 'string', description: 'Renders as data-testid on the root. See [Testing](/docs/testing).' },
}"
/>

The root carries `data-view` (`pdf`, `image`, `video`, `audio`, `text` or `none`), `data-kind` and `data-status` (`loading`, `error` or `ready`), for styling and tests. `FilePreview.Open` takes `onError`, and Button's props; `FilePreview.Download` takes DownloadButton's, except `data` and `name`.
