---
title: Upload and sync files in a Kovlet Data Space
overline: HOW-TO
nav: Upload and sync files
updated: 2026-12
minutes: 7
next: rollback
---

# Upload and sync files in a Kovlet Data Space

Store files next to your data, link them from rows, and see every change live in every app. This guide covers upload, display, versions, moves, delete and restore with `@kovlet/client`.

> **At a glance**
>
> - Declare `files: true` on the slot, and a `t.fileRef()` column to link a row to a file.
> - Upload with `space.files.upload(path, data, { mimeType })`, then store `file.id` in the row. The ID survives moves.
> - Show with `space.files.url(id)` (a short-lived URL for `<img src>`) or `space.files.download(id)` (a `Blob`, checked against its SHA-256).
> - List with `space.files.list("receipts/")`, `space.files.subscribe(cb)`, or `useFiles(space, { prefix })` in React.
> - Upload to the same path for a new version. `download(id, { version: 1 })` reads an older one. Paths: at most 1024 bytes. Files: up to 5 GiB.

Every app on the Data Space sees file changes live, as it sees rows. File details (path, size, type) sync at once. Each app downloads the file contents only when it needs them.

## Before you start

- A Kovlet server. The samples use a local `kovletd --dev` started with `--dev-auto-approve`. See [Run Kovlet locally](https://kovlet.com/docs/run-locally). Against the hosted service, leave out `url` and `consoleUrl`.
- Node.js 22 or newer, and `npm i @kovlet/client tsx` in an empty folder with `"type": "module"` in its `package.json`.
- In a browser app, the same calls work unchanged. The [web quickstart](https://kovlet.com/docs/quickstart-web) sets one up.
- Editor access to the Data Space to write files. Viewers can list and download.

## 1. Declare files and a file column

```ts title="kovlet.ts" hl="9,11"
import { createKovletClient, t } from "@kovlet/client";

export const kovlet = createKovletClient({
  appName: "Receipts",
  url: "http://127.0.0.1:8080", // kovletd --dev; leave out for https://api.kovlet.com
  consoleUrl: "http://localhost:5173", // leave out for https://kovlet.com
  spaces: {
    main: {
      files: true,
      tables: {
        receipts: { title: t.string(), scan: t.fileRef().optional() },
      },
    },
  },
});
```

- **Line 9:** `files: true` says the app uses the Data Space's files.
- **Line 11:** `t.fileRef()` is a column that holds the ID of a file in the same Data Space.

`main` is a [slot](/docs/glossary#slot "A logical space name in app code, such as main or finance, with the tables and role the app needs. The user maps each slot to a Data Space at consent."): the name your code uses for a Data Space.

Files belong to the Data Space, not to a row. Several rows can point at one file, and a file can exist with no row at all.

## 2. Upload a file and link it from a row

```ts title="upload.ts" hl="8-11"
import { readFile } from "node:fs/promises";
import { kovlet } from "./kovlet";

await kovlet.connect();
await kovlet.whenSynced();
const main = kovlet.space("main");

const file = await main.files.upload("receipts/2026/lunch.txt", await readFile("receipt.txt"), {
  mimeType: "text/plain",
});
await main.table("receipts").insert({ title: "Lunch", scan: file.id });
await kovlet.whenSynced();
console.log(main.files.get(file.id));
kovlet.disconnect();
```

`upload(path, data, { mimeType })` takes a `Blob` or `File`, an `ArrayBuffer`, a typed array or a string. `mimeType` defaults to the `Blob`'s type, or a guess from the file extension.

It returns the file entry at once. What happens next:

1. The file shows up in every list right away, with `pending: true` and `version: 0`.
2. The client keeps the bytes and uploads them in the background, or when the app is back online.
3. Only then does it commit the file to the Data Space.
4. `version` becomes `1` when the server confirms.

> **Tip:** Store `file.id` in the row, not the path. The ID stays the same when the file is moved or renamed.

In a browser, pass the `File` from an `<input type="file">`:

```ts title="attach.ts"
import { kovlet } from "./kovlet";

export async function attach(receiptId: string, input: HTMLInputElement) {
  const picked = input.files?.[0];
  if (!picked) return;
  const main = kovlet.space("main");
  const file = await main.files.upload(`receipts/${picked.name}`, picked, { mimeType: picked.type });
  main.table("receipts").update(receiptId, { scan: file.id });
}
```

Kovlet stores bytes by their SHA-256, per Data Space. If the Data Space already holds the same bytes, uploading them sends nothing over the network a second time.

## 3. List files and react to changes

```ts title="list.ts"
import { kovlet } from "./kovlet";

const main = kovlet.space("main");
console.log(main.files.list("receipts/").map((f) => `${f.path} (${f.sizeBytes} bytes)`));

const stop = main.files.subscribe((files) => console.log(`${files.length} files`));
// later: stop();
```

- `files.list(prefix)` returns live files whose path starts with `prefix`, sorted by path.
- `files.all()` returns every live file.
- `files.get(idOrPath)` returns one.
- `files.subscribe(cb)` calls `cb` with every live file whenever a file changes, from this app or any other.

Each entry has `id`, `path`, `sha256`, `sizeBytes`, `mimeType`, `version` and `pending`.

> **Note:** Lists read the local copy of the data (the local replica). In a script, call them after `await kovlet.whenSynced()`.

In React, `useFiles` re-renders on every change:

```tsx title="Receipts.tsx"
import { useFiles, useSpace } from "@kovlet/react";
import type { kovlet } from "./kovlet";

export function Receipts() {
  const main = useSpace<typeof kovlet>("main");
  const files = useFiles(main, { prefix: "receipts/" });
  return (
    <ul>
      {files.map((f) => (
        <li key={f.id}>
          {f.path}
          {f.pending ? " (uploading)" : ""}
        </li>
      ))}
    </ul>
  );
}
```

## 4. Show or download a file

```ts title="show.ts"
import { kovlet } from "./kovlet";

const main = kovlet.space("main");

export async function showScan(img: HTMLImageElement, fileId: string) {
  img.src = await main.files.url(fileId); // valid for 15 minutes; ask again after that
}

export async function readScan(fileId: string) {
  const blob = await main.files.download(fileId); // checked against the file's SHA-256
  return blob.text();
}
```

- `files.url(idOrPath)` returns a presigned URL. Anyone holding it can fetch the file until it expires, 15 minutes later. Use it for `<img src>`, `<a href>` or a native download.
- `files.download(idOrPath)` fetches the bytes as a `Blob` with the file's MIME type. It checks the SHA-256, and caches the bytes by hash.

## 5. Replace a file with a new version

Upload to the same path again. Kovlet writes a new version of the same file (same `id`) and keeps the earlier ones:

```ts title="versions.ts"
import { kovlet } from "./kovlet";

const main = kovlet.space("main");

export async function replace(path: string, data: Blob | string) {
  const file = await main.files.upload(path, data); // same path: a new version of the same file
  return main.files.download(file.id, { version: 1 }); // the first version, as a Blob
}
```

To write a new version of a specific file, wherever it lives now, pass its ID: `upload(path, data, { id: file.id })`.

`GET /v1/spaces/{space}/files/{id}/versions` lists every version, with its path, SHA-256, size, MIME type and who wrote it. Moves don't make versions.

## 6. Move, delete and restore

```ts title="organize.ts"
import { kovlet } from "./kovlet";

const main = kovlet.space("main");

export function organize(fileId: string) {
  main.files.move(fileId, "receipts/2026/01-lunch.txt"); // rename or move; the ID stays
  main.files.moveFolder("receipts/2026/", "archive/2026/"); // returns how many files it moved
}

export const trash = (fileId: string) => main.files.delete(fileId); // to the Trash
export const untrash = (fileId: string) => main.files.restore(fileId); // back, at the path it had
```

These calls apply locally at once and sync like row writes.

- `moveFolder` sends one move per file, as one batch. The server applies all of them or none.
- A deleted file goes to the [Trash](/docs/glossary#trash "Where deleted rows and files go. Deletes are soft: a trashed row or file keeps its data and can be restored."). It leaves `files.list()`, but its bytes are kept. `restore`, or the console's **Safety** → **Trash**, brings it back.
- Two live files can't share a path. A write that would make them is rejected with `path_conflict`.

## Run it end to end

This script does every step against the local server:

```ts title="files.ts"
import { readFile } from "node:fs/promises";
import { kovlet } from "./kovlet";

await kovlet.connect();
await kovlet.whenSynced();
const main = kovlet.space("main");

// Upload a file, then link it from a row by its id.
const file = await main.files.upload("receipts/2026/lunch.txt", await readFile("receipt.txt"), {
  mimeType: "text/plain",
});
await main.table("receipts").insert({ title: "Lunch", scan: file.id });
await kovlet.whenSynced();
const saved = main.files.get(file.id);
console.log("uploaded:", saved?.path, `${saved?.sizeBytes} bytes`, `version ${saved?.version}`);

// Upload to the same path again: a new version of the same file.
await main.files.upload("receipts/2026/lunch.txt", "Lunch, 14.00 EUR\n", { mimeType: "text/plain" });
await kovlet.whenSynced();
console.log("version:", main.files.get(file.id)?.version);
console.log("current:", JSON.stringify(await (await main.files.download(file.id)).text()));
console.log("version 1:", JSON.stringify(await (await main.files.download(file.id, { version: 1 })).text()));

// Move it, rename its folder, then delete and restore it.
main.files.move(file.id, "receipts/2026/01-lunch.txt");
console.log("moved:", main.files.moveFolder("receipts/2026/", "archive/2026/"), "file");
main.files.delete(file.id);
await kovlet.whenSynced();
console.log("after delete:", main.files.list().map((f) => f.path));
main.files.restore(file.id);
await kovlet.whenSynced();
console.log("after restore:", main.files.list().map((f) => f.path));
kovlet.disconnect();
```

```sh title="terminal"
printf 'Lunch, 12.50 EUR\n' > receipt.txt
npx tsx files.ts
```

> **You should see**
>
> - The upload at version 1, then version 2 after the second upload.
> - Both versions' contents, the move, an empty list after the delete, and the file back after the restore.

```text title="output"
[kovlet] To connect Receipts, open http://localhost:5173/activate?user_code=ZZZU-72J2 and confirm code ZZZU-72J2
uploaded: receipts/2026/lunch.txt 17 bytes version 1
version: 2
current: "Lunch, 14.00 EUR\n"
version 1: "Lunch, 12.50 EUR\n"
moved: 1 file
after delete: []
after restore: [ 'archive/2026/01-lunch.txt' ]
```

## Other platforms

| Platform | Upload | Download |
| --- | --- | --- |
| `@kovlet/client` (browser, Node, Electron) | `space.files.upload(path, data, { mimeType })` | `space.files.download(id)`, `space.files.url(id)` |
| `@kovlet/client` with your own `store` ([Node quickstart](https://kovlet.com/docs/quickstart-node#5-files)) | not in this mode: create the client without `store`, or use REST | `space.files.download(id)`, `space.files.url(id)` |
| Rust and Tauri | `space.files().put_file(path, &local_path, mime, None)` or `put(path, &bytes, mime, None)` | `space.files().download(&id, &target)` |
| Swift | `space.files.put(path:data:mimeType:)`, `put(path:contentsOf:mimeType:)` | `space.files.download(id:to:)` |
| Android | `space.files.put(path, bytes, mimeType)`, `put(path, file, mimeType)` | `space.files.download(id, file)` |
| REST + WebSocket | `POST /v1/spaces/{space}/files/uploads`, send the bytes, then a file `put` mutation ([REST quickstart](https://kovlet.com/docs/quickstart-rest#4-files)) | `GET /v1/spaces/{space}/files/{id}/download` |

The native SDKs stage uploads on disk and send them in the background, so they work offline too.

Over REST:

- `GET /v1/spaces/{space}/files?dir=receipts/` lists one folder level.
- `POST /v1/spaces/{space}/files/move-folder` renames a folder in one transaction.
- `POST /v1/spaces/{space}/files/{id}/restore` takes a file out of the Trash.

The [OpenAPI spec](https://kovlet.com/openapi.json) has every file route.

## Limits

- **Paths:** relative, `/`-separated, at most 1024 bytes. No empty, `.` or `..` segments, no leading `/`, and no NUL or backslash. `upload` and `move` throw `KovletValidationError` (`reason: "invalid_path"`) before anything is sent.
- **Size:** 5 GiB per file. A larger upload is rejected with `too_large` (HTTP 413).
- **Storage:** file bytes count toward the workspace's `storage` quota: 1 GiB on the free plan, 50 GiB on Pro, 500 GiB on Org. A new upload that would not fit is rejected with `quota_exceeded` (`metric: "storage"`). Downloads, moves, deletes and restores keep working.
- **Download URLs:** valid for 15 minutes.

Sometimes the server refuses an upload for good (`quota_exceeded`, `too_large`). Then the client removes the file entry it showed, and reports a `MutationRejectedError` through `kovlet.onError`. A network failure is not a refusal: the client retries the upload.

## Troubleshooting

| What you see | Why | What to do |
| --- | --- | --- |
| A file stays `pending: true` | The bytes haven't uploaded yet: the app is offline or the upload is retrying. | Wait for the connection; `kovlet.whenSynced()` resolves once it's committed. |
| `quota_exceeded` with `metric: "storage"` | The workspace's file storage is full. | Request a higher plan with the upgrade form in the console (`upgrade_url`). |
| `path_conflict` | Another live file already has that path. | Pick another path, or move or delete the other file first. |
| `not_found` from `move`, `delete`, `download` or `url` | No live file with that ID or path in the local replica. | `await kovlet.whenSynced()` first, and check `files.list()`. |
| The image URL stops working | Presigned URLs expire after 15 minutes. | Call `files.url(id)` again when you render. |
| `forbidden` with `reason: "insufficient_role"` | The app has viewer access to the Data Space. | Ask an owner for editor access, or only read. |

Every error code is in the [errors and limits reference](https://kovlet.com/docs/errors-and-limits).

## Next

- [Roll back an app's changes](https://kovlet.com/docs/rollback): undo and point-in-time restore cover files too.
- [Evolve a schema and approve proposals](https://kovlet.com/docs/evolve-schema): add a `t.fileRef()` column to an existing table.
- [Kovlet sync protocol reference](https://kovlet.com/docs/protocol): the upload flow and file ops on the wire.
