> ## Documentation Index
> Fetch the complete documentation index at: https://docs.widgetic.com/llms.txt
> Use this file to discover all available pages before exploring further.

# File Browser

> Let your customers browse, upload and pick files in your page, from Widgetic's media library or from your own

The **File Browser** is a media library in your page: a customer browses their folders and files, filters them by kind, searches and sorts, uploads by dropping files, and picks the files your page needs (see it in [the gallery](https://docs.widgetic.com/docs/partners/ui-components#the-pieces)). By default the files are the customer's own, kept in your own [storage](https://docs.widgetic.com/docs/partners/storage.md). Or the files are **yours**: give it your own [media library](#show-your-own-media-library) and it lists, uploads, renames and deletes your files, with no Widgetic session at all.

Like every piece, it is mounted with the [UI SDK](https://docs.widgetic.com/docs/partners/ui-components#mount-a-piece). Its [editor session](https://docs.widgetic.com/docs/partners/editor-sessions.md) needs the surface `files`, and nothing at all when you give it your own media library. Installing the SDK, tokens, the theme, the language and the Content Security Policy are the same for every piece, and are on [the UI Components page](https://docs.widgetic.com/docs/partners/ui-components). This page covers what is specific to the File Browser.

## Options

| Option | |
| - | - |
| `maxSelections` | How many files can be picked at once. `1` makes it a single-file picker. Default: any number. |
| `initialFilter` | Which kind of file to show first: `'all'` (the default), `'image'`, `'audio'`, `'video'`, `'document'`, `'font'` or `'svg'`. The customer can change it. |
| `allowSelecting` | `true` (the default) makes it a picker: the customer ticks files and a button hands them to your page. `false` makes it a library page, where the customer only adds and edits files: nothing can be ticked and there is no confirm button. |
| `selectLabel` | The text of the button that hands the pick to your page. Default `Select`. `messages['action.addToEditor']` does the same and wins when both are given. |
| `mediaLibrary` | Your own files instead of the customer's Widgetic uploads. See [Show your own media library](#show-your-own-media-library). |
| `locale`, `messages` | The File Browser's language: `locale` brings its words in 65 languages, `messages` changes the ones you want to say differently. See [Show the pieces in the language of your customers](https://docs.widgetic.com/docs/partners/ui-components#show-the-pieces-in-the-language-of-your-customers). |
| `theme`, `apiUrl`, `getToken` | As for every piece. `getToken` is not needed with your own `mediaLibrary`. |

## Events

| Event | Payload | |
| - | - | - |
| `ready` | | The File Browser is on screen. |
| `select` | `{ files: [{ id, name, url, mimeType?, size?, thumbnail? }] }` | The customer confirmed a pick. |
| `error` | `{ message, code?, fatal, action?, file? }` | As for every piece. When your own [media library](#show-your-own-media-library) fails, it adds `action` (what the customer was doing: `load`, `upload`, `rename` or `delete`) and, for an upload, `file` (its name). |

* **One File Browser per page.** A second one is refused with a clear message. Unmount the first before you mount another.
* **A file over 10 MB.** An editor session cannot use the resumable upload, so a file over 10 MB is refused with a message instead of being sent.

## Show your own media library

If your platform already has a media library (a CMS, an S3 bucket, a DAM), give the File Browser plain functions that read and write it. Your customers browse, upload and pick from **your** files with the same screen. The piece then never talks to Widgetic, so there is no session to make and no `getToken`.

```javascript theme={"theme":"css-variables"}
const fileBrowser = await mountModule('file-browser', {
  container: '#media-library',
  mediaLibrary: {
    id: 'acme-assets',
    label: 'Acme assets', // shown as the list's title. Default "My uploads"
    // Required. One page of files, newest first. `cursor` is the `nextCursor` you returned for the page before.
    list: async ({ cursor, limit, signal }) => {
      const response = await fetch(`/api/assets?cursor=${cursor ?? ''}&limit=${limit}`, { signal });
      if (!response.ok) throw Object.assign(new Error('Could not load your files'), { status: response.status });
      const page = await response.json();
      return {
        items: page.assets.map((asset) => ({ id: asset.id, name: asset.fileName, url: asset.publicUrl, mimeType: asset.contentType })),
        nextCursor: page.next ?? null, // null: that was the last page
      };
    },
    // Optional. A button is shown only for the functions you give.
    upload: async ({ file, onProgress, signal }) => uploadToAcme(file, onProgress, signal), // return the stored file
    rename: async ({ id, name, signal }) => renameInAcme(id, name, signal),
    delete: async ({ id, signal }) => deleteInAcme(id, signal),
  },
  on: {
    select: ({ files }) => useFiles(files), // your files, as your library described them
    error: ({ message, code, action }) => report(code, action, message),
  },
});
```

* A failure inside your functions is reported through the `error` event with `fatal: false`. The File Browser shows the customer a list that cannot be read (with "Try again"), an upload that fails (in the upload panel) and a `rename` or `delete` that your library refuses (in a pop-up, with your library's sentence under it): the file stays as it was, and your page hears of it as well, so use the event for your log, not for a second message. The code is `MEDIA_LIBRARY_` plus `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `NETWORK`, `INVALID_RESPONSE`, `NOT_SUPPORTED` or `FAILED`, and `action` says what the customer was doing (`load`, `upload`, `rename` or `delete`). Throw an error with a `status` property (a failed `fetch` response) and it is sorted for you.
* Everything your functions return is checked before it is shown. A file without an id, a name or a usable address is skipped with a console warning rather than breaking the list.
* The `url` of a file is what a widget stores and shows. Once your customer saves or publishes, everyone who sees the widget loads that address, not only the customer who picked it: give one that stays valid and needs no sign-in. A link that expires after a few minutes, or one that checks a cookie, breaks the published widget. Widgetic keeps the `id` with the file only so that the picker shows it as selected when it is opened again.
* The [Composition Editor](https://docs.widgetic.com/docs/partners/ui-components/composition-editor.md) and the [Widget Creator](https://docs.widgetic.com/docs/partners/ui-components/widget-creator.md) take the same `mediaLibrary`: their file pickers then show your files. When you also give `upload`, the Widget Creator's chat attachments and the pictures dropped on its canvas call it too, once per file, with `purpose` set to `'chat'` or `'canvas'` (the pickers pass `'field'`).
* Text, PDF and font previews read the file with a script, so a file on another website needs an `Access-Control-Allow-Origin` header for your page's origin. Pictures, audio and video are shown without it.

The types of your library and of the files it handles are exported from `@widgetic/ui-sdk` (`PartnerMediaLibrary`, `MediaLibraryFile`, `PickFileFn` and `PickFileRequest` among them), so your functions are checked when you write them.

## Your own file picker for the editors

The Composition Editor and the Widget Creator open the File Browser when a file field needs a file. If your platform already has a picker of its own, give them `pickFile` and they call it instead:

```javascript theme={"theme":"css-variables"}
const editor = await mountModule('composition-editor', {
  container: '#editor',
  compositionId,
  getToken,
  pickFile: async ({ accept, multiple, signal }) => {
    const chosen = await myPicker.open({ types: accept, many: multiple, cancel: signal });
    return chosen.map((file) => ({ id: file.id, name: file.name, url: file.publicUrl, mimeType: file.type }));
  },
});
```

* `accept` lists the file types the field allows (`['image/*']`, for example), and `['*/*']` when it names none. `multiple` is `false` for the file fields of a widget, and a field takes the first file of the list you return. `signal` aborts when the customer closes the editor or starts another pick.
* Return `[]`, or reject with an `AbortError`, when the customer cancelled. Any other rejection is written to the console once and counts as nothing picked: the field stays as it was and the customer sees nothing, so say it in your own picker.
* A result that is not a list is ignored with a warning in the console, and so is an entry that has no `id` or no `url`.
* `pickFile` serves file fields only. A chat attachment and a picture dropped on the Widget Creator's canvas go through `mediaLibrary.upload` when you give one.

## Next Steps

> [card] [Editor Sessions](https://docs.widgetic.com/docs/partners/editor-sessions.md)
>
> Make the token on your server

> [card] [UI Components](https://docs.widgetic.com/docs/partners/ui-components)
>
> The SDK, tokens, the look and the language of every piece

> [card] [Storage](https://docs.widgetic.com/docs/partners/storage.md)
>
> Where your customers' uploads are kept

> [card] [Content Security Policy](https://docs.widgetic.com/docs/partners/ui-components#content-security-policy)
>
> What your page has to allow


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.