# Files

> File storage per application — attachments, images people send, generated exports — served and received by your own routes, shared by every version.

An application can keep files: attachments, images its users send, exports it generates. A database row
holds 2 MB at most, a file in storage up to 5 TiB.

The browser never reads or writes the storage directly: **your application serves and receives its files
through its own routes.** There is no signed URL, no storage key of its own, no CORS to set up. Every file
received or served goes through your code, which alone decides who may read it.

## Declare it

```json
"x-apigami": { "files": true }
```

`false` is the default, and an application that declares nothing has no file storage. It is created the first
time a version declaring it runs or deploys, before your code starts; a try or a deployment that cannot get it
stops with the reason, rather than running without `env.FILES`. Once it exists, it stays, even for a version
that stops declaring it: going back to an earlier version never loses access to files already written.

A file that reads `env.FILES` while the manifest declares no storage gets the warning `files_not_declared`.
`FILES` is a reserved name, like `DB` and `ASSETS`: no environment variable may take it.

**Every version shares the files**, as it shares the database: a try that writes or deletes a file changes
what production reads. Putting another version in production copies and restores nothing.

## What your code calls

Your code reads the storage as `env.FILES`, on a try as in production:

| Call | What it does |
|---|---|
| `get(key, { range?, onlyIf? })` | The object and its body, or `null`. `range` is `{ offset, length }`, `{ offset }` or `{ suffix }` |
| `head(key)` | The object without its body, or `null` |
| `put(key, body, { httpMetadata?, customMetadata?, onlyIf? })` | Writes the object: `body` is a stream, a string, an `ArrayBuffer` or a `Blob`. Answers the object |
| `delete(key)` or `delete([key, …])` | Removes one key, or up to 1,000 at once. A missing key is no error |
| `list({ prefix?, cursor?, limit?, delimiter? })` | `{ objects, truncated, cursor, delimitedPrefixes }`, 1,000 objects a page at most |
| `createMultipartUpload(key, options?)`, `resumeMultipartUpload(key, uploadId)` | An upload in several parts: `uploadPart(partNumber, body)`, `complete(parts)`, `abort()` |

An object carries `key`, `size`, `etag`, `httpEtag` (the same, quoted, as an `ETag` header wants it),
`uploaded`, `httpMetadata` (`contentType`, `contentDisposition`, `cacheControl`…), `customMetadata` (your own
strings) and, from `get` with a `range`, the `range` it answered. `object.writeHttpMetadata(headers)` copies its
`httpMetadata` into response headers. On a try, an option the storage cannot honour throws an error that names
it, never a silent difference.

## Who may read a file

Nothing in the storage knows a person: a key is a string, and anyone your routes answer reads what they
answer. Check the person on every route, and put their `user_ref` in the key of what belongs to them. A route
of your app's own address reads the person in `x-apigami-user-ref`, null for a visitor
([The person behind a page](/docs/app-page-sessions/#who-is-behind-a-request-x-apigami-user-ref)); an action
reads it from `GET /v1/me` ([Its database](/docs/app-database/#its-database)). Never take the owner of a file
from the path or the input alone.

## Serve a file

The route below answers `GET /files/{name}` with the person's file, its headers, `304` when the browser
already has it, and a part of it for a `Range` request, which a video player or a resumed download sends:

```ts title="files/serve.ts"
// "bytes=500-999", "bytes=500-" or "bytes=-500"; anything else, or several ranges, serves the whole file.
const rangeOf = (header: string | null, size: number) => {
  const match = header?.match(/^bytes=(\d*)-(\d*)$/)
  if (!match || (match[1] === '' && match[2] === '')) return null
  if (match[1] === '') return { offset: Math.max(size - Number(match[2]), 0), length: Math.min(Number(match[2]), size) }
  const offset = Number(match[1])
  const last = match[2] === '' ? size - 1 : Math.min(Number(match[2]), size - 1)
  return { offset, length: last - offset + 1 }
}

export const serveFile = async (request: Request, env, name: string) => {
  const userRef = request.headers.get('x-apigami-user-ref')
  if (!userRef) return new Response('Sign in to see this file', { status: 401 })
  const key = `${userRef}/${name}`

  const object = await env.FILES.head(key)
  if (!object) return new Response('Not found', { status: 404 })

  const headers = new Headers()
  object.writeHttpMetadata(headers)
  headers.set('ETag', object.httpEtag)
  headers.set('Accept-Ranges', 'bytes')
  headers.set('Cache-Control', 'private, max-age=0, must-revalidate')
  if (request.headers.get('If-None-Match') === object.httpEtag) return new Response(null, { status: 304, headers })

  const range = rangeOf(request.headers.get('Range'), object.size)
  if (range && (range.length <= 0 || range.offset >= object.size)) {
    headers.set('Content-Range', `bytes */${object.size}`)
    return new Response(null, { status: 416, headers })
  }
  // The etag pins the version head() saw: a file replaced in between answers no body rather than mixed bytes.
  const file = await env.FILES.get(key, { range: range ?? undefined, onlyIf: { etagMatches: object.etag } })
  if (!file || !('body' in file)) return new Response('The file changed, try again', { status: 409 })

  if (!range) return new Response(file.body, { headers })
  headers.set('Content-Range', `bytes ${range.offset}-${range.offset + range.length - 1}/${object.size}`)
  return new Response(file.body, { status: 206, headers })
}
```

A `HEAD` request is answered by the same route without the `get`. Keep the `404` for a key that does not
exist: a catch-all `200` would also hide every file of `public/`
([Static files](/docs/app-server/#static-files-public)). On a [version built by Vite](/docs/app-server/#pages-built-by-vite)
the files of `dist/` are served before your code, and a path outside the first segment of every action answers
`index.html`: serve stored files from a path under an action's, such as `/api/files/{key}`.

## Receive a file

A page sends a file to a route of your own address, and the route streams the request body into storage
without holding it in memory, which 128 MB would not fit:

```ts title="files/receive.ts"
const MAX_REQUEST_BYTES = 100 * 1000 * 1000

export const receiveFile = async (request: Request, env, name: string) => {
  const userRef = request.headers.get('x-apigami-user-ref')
  if (!userRef) return new Response('Sign in to send a file', { status: 401 })
  // A streamed body is only stored with its length known in advance: a browser's fetch(File) sends it.
  const length = Number(request.headers.get('Content-Length'))
  if (!length) return new Response('Content-Length is required', { status: 411 })
  if (length > MAX_REQUEST_BYTES) return new Response('Larger than 100 MB: send it in parts', { status: 413 })

  const object = await env.FILES.put(`${userRef}/${name}`, request.body, {
    httpMetadata: {
      contentType: request.headers.get('Content-Type') ?? 'application/octet-stream',
      contentDisposition: `attachment; filename="${name.replace(/["\\]/g, '')}"`,
    },
    customMetadata: { sent_at: new Date().toISOString() },
  })
  return Response.json({ key: object.key, size: object.size, etag: object.etag }, { status: 201 })
}
```

In the page, `fetch('/files/' + encodeURIComponent(file.name), { method: 'PUT', body: file, headers: {
'Content-Type': file.type } })` sends it with its length and its type. Check the type and the size your
application accepts before the `put`, and never serve a file someone sent as HTML from your own address:
`contentDisposition: attachment` makes the browser download it instead.

### Larger than 100 MB: in parts

A request your address receives weighs 100 MB at most. Beyond, the page cuts the file and sends one part per
request; the routes create the upload, store each part, then complete it:

```ts title="files/parts.ts"
// POST /uploads/{name}: answers the upload_id the page sends back with every part.
export const startUpload = async (env, userRef: string, name: string) => {
  const upload = await env.FILES.createMultipartUpload(`${userRef}/${name}`)
  return Response.json({ upload_id: upload.uploadId })
}

// PUT /uploads/{name}/{upload_id}/{part_number}: one part, numbered from 1.
export const storePart = async (request: Request, env, userRef: string, name: string, uploadId: string, partNumber: number) => {
  const upload = env.FILES.resumeMultipartUpload(`${userRef}/${name}`, uploadId)
  const part = await upload.uploadPart(partNumber, request.body)
  return Response.json(part) // { partNumber, etag }, which the page collects for the last step.
}

// POST /uploads/{name}/{upload_id}/complete, with the parts as its JSON body.
export const completeUpload = async (request: Request, env, userRef: string, name: string, uploadId: string) => {
  const upload = env.FILES.resumeMultipartUpload(`${userRef}/${name}`, uploadId)
  const object = await upload.complete(await request.json())
  return Response.json({ key: object.key, size: object.size, etag: object.etag })
}
```

Every part but the last weighs the same, 5 MiB at least: 50 MiB parts suit a page. An upload abandoned
midway keeps its parts until `abort()`. The `userRef` in each key is the one the route read from
`x-apigami-user-ref`, never from the page.

## How large, how often

| | Limit |
|---|---|
| One object | 5 TiB, through an upload in parts (10,000 parts) |
| One `put` in a single piece | 5 GiB |
| A file received from a browser | the size of one incoming request, 100 MB; beyond, an upload in parts over several requests |
| A key | 1,024 bytes; its metadata 8 KB |
| Writes to the same key | one per second |
| Total volume | no fixed cap, billed by the GB |

File storage costs nothing to an application that keeps no files, and serving a file costs nothing either:
what counts is the volume kept and the number of writes and reads. Delete what no longer serves.

## Look at them from your assistant

Over MCP, `app_file_storage` lists the keys under a `prefix`, a page of up to 100 with the `cursor` of the next,
each with its size, upload time and content type; with a `key`, it reads that one file's metadata and gives a
link valid 10 minutes that downloads it, for the assistant or for you, never its content in the answer. The link
stops once the file is replaced or deleted, or once you leave the group. `app_file_storage_write` writes one
file of 256 KB at most from `text` or `base64`, or deletes a key or up to 1,000 `keys` with `confirm: true`.
Both act on the storage every version shares: what they list or change is what production reads. Only a
member of the application's group reaches them, never its code or its key. The files of a version, its code,
its manifest and `public/`, are not in this storage: `app_version` with a `path` reads them.

To put a larger file in storage while trying a version, or a file a person sends, go through a route of
your address that streams it, as above. Never pass a file through `app_run`'s `input`: it travels as JSON,
so as base64 a third larger, and it is bounded like any request body.

## Deleting

Deleting a version deletes no file. Deleting the application keeps its files 30 days, during which they can
still be restored, then deletes them. To restore them, write to contact@apigami.com: the files come back for
every version, since they share them.