---
title: Store files
description: Declare a bucket on a luna type, then store, read, list, copy, move and delete each luna's files from its handlers.
related:
  - /files-and-code/upload-from-an-app
  - /sdk/bucket
  - /cli/files
---

Images, PDFs and exports do not belong in a table row. Declare a bucket on the luna type, and each luna keeps its own files beside its tables.

## Store a file and read it back

Name each bucket under `blobs` with [`bucket`](/sdk/bucket), then use it as `ctx.blobs.<name>`.

```ts luna/lunas/list.ts {1,10-12,14-20}
import { bucket, defineLuna, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  visibility: "public",
  key: { id: t.string() },
  schema: {
    items: table({ id: t.id(), text: t.string() }),
  },
  blobs: {
    attachments: bucket({ path: "items/{item}/{file}" }),
  },
  handlers: (h) => ({
    attach: h({ args: { item: t.int(), file: t.string(), text: t.string() } }, async (ctx, { item, file, text }) => {
      const object = await ctx.blobs.attachments.put(`items/${item}/${file}`, text);
      return object.size;
    }),
    attachment: h({ args: { item: t.int(), file: t.string() } }, (ctx, { item, file }) => {
      return ctx.blobs.attachments.text(`items/${item}/${file}`);
    }),
  }),
});
```

`put` takes a string or a `Uint8Array` and replaces whatever was at the path. `text` returns the file as UTF-8, or `null` when there is none.

The file is stored with the handler's other writes. If the handler fails, the file is not kept, the same as its rows.

## Fit paths to the bucket

Every path must fit the bucket's `path` template. A `{name}` segment matches one segment, and a `{name...}` segment, which must come last, matches all the rest. A path that does not fit fails with [`Invalid`](/errors/invalid).

| Template | Fits | Does not fit |
| --- | --- | --- |
| `items/{item}/{file}` | `items/4/receipt.pdf` | `items/4/scans/receipt.pdf` |
| `files/{rest...}` | `files/2026/scans/receipt.pdf` | `files` |

A path is at most 1,024 characters long.

## Read part of a file

`get` returns the file's bytes with its details, and `head` returns the details alone. Pass `range` to read the bytes from `from` up to, but not including, `to`.

```ts luna/lunas/list.ts
peek: h({ args: { path: t.string() } }, async (ctx, { path }) => {
  const info = ctx.blobs.attachments.head(path);
  if (!info) return null;
  const start = await ctx.blobs.attachments.get(path, { range: [0, 1024] });
  return { type: info.contentType, size: info.size, first: start?.bytes.length };
}),
```

One `put` or `get` moves at most 256 MiB. Read a larger file in ranges, or hand an app a URL with [Upload from an app](/files-and-code/upload-from-an-app).

Each call returns a `BlobObject`.

| Field | Holds |
| --- | --- |
| `bucket`, `path` | Where the file is |
| `hash` | A value that changes whenever the bytes change. The same bytes give the same hash |
| `size` | Its size in bytes |
| `contentType` | Its content type |
| `meta` | Its metadata, or `null` |
| `created`, `updated` | Milliseconds since the Unix epoch |

## Limit what a bucket takes

A bucket can limit the content types and sizes it takes, and give each file typed metadata.

```ts luna/lunas/list.ts
exports: bucket({
  path: "exports/{name}",
  types: ["text/csv"],
  maxSize: 10 * 1024 * 1024,
  meta: t.object({ rows: t.int() }),
}),
```

```ts luna/lunas/list.ts
await ctx.blobs.exports.put("exports/items.csv", csv, { contentType: "text/csv", meta: { rows: items.length } });
```

| Option | Does |
| --- | --- |
| `path` | The template every path must fit |
| `types` | Content types it takes, such as `"image/png"` or `"image/*"`. Any type when left out |
| `maxSize` | The largest file in bytes. 10 GiB by default, and at most 10 GiB |
| `meta` | The type each file's metadata must match. At most 16 KiB as JSON |
| `public` | Lets anyone read its files at a plain URL. See [Upload from an app](/files-and-code/upload-from-an-app) |

Without `contentType`, a string is stored as `text/plain; charset=utf-8` and bytes as `application/octet-stream`. A file the bucket does not take fails with `Invalid`.

## List the files

`list` returns files in path order, 100 at a time unless you pass `limit`, and at most 1,000. Pass the returned `cursor` back for the next page. It is `null` after the last.

```ts luna/lunas/list.ts
let cursor: string | null = null;
do {
  const page = ctx.blobs.attachments.list({ prefix: `items/${item}/`, cursor });
  paths.push(...page.objects.map((o) => o.path));
  cursor = page.cursor;
} while (cursor);
```

## Copy, move and delete files

`copy` and `move` take a path in the same bucket, or `{ bucket, path }` for another bucket of the luna. The destination bucket's rules apply. A copy shares the bytes, so it does not store them twice.

```ts luna/lunas/list.ts
ctx.blobs.attachments.copy(path, { bucket: "archive", path });
ctx.blobs.attachments.move(path, `items/${item}/old-${file}`);
const deleted = ctx.blobs.attachments.delete(path);
```

`copy` and `move` return the new `BlobObject`, or `null` when there was nothing at the path. `delete` returns `false` when there was nothing to delete.

:::warning
`delete` removes the file, and a `put` to a path in use replaces it. Your code has no way to read the old bytes after either.
:::

## Point rows at files

A [`t.blobRef(bucket)`](/sdk/t) column holds the path of a file in that bucket. A row must name a file that exists, and a `move` within the bucket updates the rows that point at the file.

```ts luna/lunas/list.ts
links: table({ id: t.id(), item: t.int(), file: t.blobRef("attachments", { onDelete: "cascade" }) }),
```

`onDelete` says what deleting the file does. With `restrict`, the default, the `delete` fails while a row points at the file. `cascade` deletes those rows, and `setNull` clears the column, which must be optional.

## Manage files from the CLI

[`luna files`](/cli/files) lists, downloads, uploads and deletes a luna's files, and prints a signed download URL.

```bash
luna files list List groceries attachments items/4/
```

```bash
luna files put List groceries attachments items/4/receipt.pdf ./receipt.pdf
```

An upload from the CLI goes through the bucket's checks and its `onUpload` hook, like one from an app. In the Console, open the environment, then the luna type, and select a bucket under **Files** to browse each luna's files.

## Next steps

- [Upload from an app](/files-and-code/upload-from-an-app) sends files from a browser or phone without passing them through a handler.
- [Run a sandbox](/files-and-code/run-a-sandbox) copies files between a bucket and a sandbox's disk.
- [bucket](/sdk/bucket) lists every option and method.
