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

# File uploads

> Upload files from the browser with useUpload, save them to attachments fields, and show customers file links on the app's own domain.

Use the `useUpload` hook from `zitejs/upload` to upload files from a page: avatars, attachments, images,
documents. It stores the file and returns a permanent URL, which you save in an attachments field or any
other field.

## Upload from a page

`useUpload()` returns an `upload` function and an `isUploading` flag:

```tsx theme={"system"}
import { useUpload } from 'zitejs/upload';

const { upload, isUploading } = useUpload();

const { url } = await upload(file); // a File
const { url: signature } = await upload(dataUrl, 'signature.png'); // a Blob, ArrayBuffer or data: URL, plus a filename
```

| Call | Takes | Resolves to |
| - | - | - |
| `upload(file)` | A `File` | `{ url }` |
| `upload(data, filename)` | A `Blob`, an `ArrayBuffer`, or a base64 `data:` URL, plus a filename | `{ url }` |

* **`url` is the file's permanent, canonical URL.** Save it unchanged in database fields.
* **The filename's extension sets the stored file type**, so include it: `'signature.png'`, not
  `'signature'`.
* **`upload()` never fetches a URL string**, a `blob:` URL included. It stores the string itself as a text
  file. Upload the `File` or `Blob` instead.
* **`upload()` runs only in the browser.** There is no server-side upload. When a server function produces
  file data, return it to the page and upload it from there.

## Save to an attachments field

An attachments field accepts only two kinds of value:

* **Attachment objects read from a record.** Reading an attachments field returns `ZiteAttachment[]`, each
  `{ filename, originalName, size, mimeType, url, uploadedAt, metadata? }`.
* **Public, direct-download `http(s)` URLs**, either as a string or as `{ url, filename? }`. Include the
  extension in `filename`.

Anything else is dropped without throwing, and the record still saves. That covers `data:` and `blob:`
URLs, base64, bytes, relative paths, and empty strings.

> [!WARNING]
>
> A write replaces the field's whole list. To add a file, read the record's current attachments in the server
> function and write them back with the new one. To keep the field unchanged, leave it out of the write.

This page uploads a file, then a mutation's server function appends it to a ticket's `files` field and refreshes every query of the `tickets` table:

```tsx theme={"system"}
// apps/<app>/src/components/AttachFile.tsx
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { useUpload } from 'zitejs/upload';
import { addTicketFile } from '../lib/tickets.functions';

export function AttachFile({ ticketId }: { ticketId: string }) {
  const { upload } = useUpload();
  const queryClient = useQueryClient();
  const attach = useMutation({
    mutationFn: async (file: File) => {
      const { url } = await upload(file);
      await addTicketFile({ data: { ticketId, url, filename: file.name } });
    },
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['tickets'] }),
    onError: error => toast.error(error.message),
  });

  return (
    <input
      type="file"
      disabled={attach.isPending}
      onChange={event => {
        const file = event.target.files?.[0];
        if (file) attach.mutate(file);
      }}
    />
  );
}
```

```typescript theme={"system"}
// apps/<app>/src/lib/tickets.functions.ts
import { z } from 'zod';
import { signedInFn, ZiteError } from 'zitejs/start';
import { zite } from 'zitejs/db';

export const addTicketFile = signedInFn({
  method: 'POST',
  description: 'Attaches an uploaded file to a ticket the signed-in user filed',
})
  .validator(z.object({ ticketId: z.string(), url: z.string(), filename: z.string() }))
  .handler(async ({ data, context }) => {
    const ticket = await zite.tickets.findOne({ id: data.ticketId });
    if (!ticket || ![ticket.createdBy ?? []].flat().includes(context.user.id)) {
      throw new ZiteError('NOT_FOUND', 'No such ticket');
    }
    await zite.tickets.update({
      id: ticket.id,
      record: { files: [...(ticket.files ?? []), { url: data.url, filename: data.filename }] },
    });
  });
```

## Show file links on the app's domain

Uploaded files are stored on Zite's upload hosts. When the app offers a customer-facing file URL (a
copy-link button, a download link, an image URL), derive a branded URL on the app's own domain at render or
copy time. Don't replace the stored canonical URL.

| Canonical URL | Branded URL |
| - | - |
| `https://uploads.zite.com/<key>` | `${window.location.origin}/api/file/us/<key>` |
| `https://eu-uploads.zite.com/<key>` | `${window.location.origin}/api/file/eu/<key>` |

* Rewrite only these two exact upload hosts. Leave every other URL unchanged.
* Use the canonical URL during local development.
* Branded URLs stay valid when viewed through the app's published Zite domain or its custom domain. Keeping
  the canonical URL in storage means changing a custom domain doesn't break saved files.

```typescript theme={"system"}
// apps/<app>/src/lib/fileUrl.ts
const UPLOAD_HOSTS = [
  ['https://uploads.zite.com/', 'us'],
  ['https://eu-uploads.zite.com/', 'eu'],
] as const;

export const brandedFileUrl = (canonicalUrl: string, origin: string) => {
  for (const [host, region] of UPLOAD_HOSTS) {
    if (canonicalUrl.startsWith(host)) {
      return `${origin}/api/file/${region}/${canonicalUrl.slice(host.length)}`;
    }
  }
  return canonicalUrl;
};
```

`window` exists only in the browser, and pages render on the server first. Call the helper in an event
handler, such as a copy button's
`onClick={() => navigator.clipboard.writeText(brandedFileUrl(file.url, window.location.origin))}`, or
inside `<ClientOnly>` from `@tanstack/react-router`.

## Size limits

The per-file size limit follows the workspace's plan. Larger files are rejected.

| Plan | Max file size |
| - | - |
| Free | 20 MB |
| Pro | 50 MB |
| Business | 1 GB |
| Team | 5 GB |
| Enterprise | 10 GB |


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