# File Uploads & Downloads

- **Section:** Core Concepts
- **URL:** https://refast.fastapicloud.dev/docs/concepts/file-transfers
- **Markdown:** https://refast.fastapicloud.dev/docs/concepts/file-transfers.md
- **Source:** https://github.com/idling-mind/refast-docs/blob/main/docs/pages/concepts/file_transfers.py
- **Live examples:** the widgets on this page need a browser; open the URL above to try them.
- **Applies to:** refast 0.12.2

Refast provides first-class support for file uploads from the browser and
programmatic file downloads triggered from server callbacks.

## Upload Flow

```
Browser → FileUploader → /api/upload → callback(ctx)
```

The `FileUploader` component handles chunked upload, progress reporting, and drag-and-drop.
Your Python callback receives file metadata via `ctx.event_data` and can read the uploaded
bytes via the returned file ID.

## Download Flow

```
Python callback → ctx.create_file_url() → ctx.trigger_download()
```

Your callback generates data in memory, registers it as a temporary file URL, then instructs
the browser to download it — all without any extra HTTP endpoints.

### Live Demo — Image Uploader

Drop an image (PNG, JPG, GIF, WebP — max 5 MB).

## FileUploader

```python
from refast.components import FileUploader

FileUploader(
    label="Drop files here",
    description="PDF, PNG up to 10 MB",
    variant="dropzone",           # "dropzone" (default) or "button"
    accept="image/*",             # MIME type filter (optional)
    multiple=False,               # Allow multiple file selection
    max_files=5,                  # Max number of files (when multiple=True)
    max_size=10 * 1024 * 1024,    # Max file size in bytes
    drag_drop=True,               # Enable drag-and-drop (button variant)
    on_select=ctx.callback(on_select),                          # Files selected
    on_upload_complete=ctx.callback(on_done),                   # Upload finished
    on_upload_error=ctx.callback(on_error),                     # Upload failed
    on_remove=ctx.callback(on_removed),                         # File removed from list
)
```

### Callback event data shapes

| Callback | `ctx.event_data` keys |
|---|---|
| `on_select` | `{"files": [{id, name, size, content_type}]}` |
| `on_upload_complete` | `{"files": [{id, name, size, content_type}]}` |
| `on_upload_error` | `{"error": "message", "file": {name, ...}}` |
| `on_remove` | `{"file": {name, size, ...}}` |

### App-level upload limits

Configure the maximum number of files and the total upload size per request on
`RefastApp`. These limits are enforced server-side and apply to every upload
regardless of what the `FileUploader` component allows client-side.

```python
from refast import RefastApp
from refast.utils.temp_file_store import MemoryFileStore

ui = RefastApp(
    title="My App",
    # Accept at most 5 files per upload request (default: 20)
    max_upload_files=5,
    # Reject a request when the combined size of all files exceeds 50 MB
    # (default: None — no total-size cap; individual files are still
    #  capped by the file store's max_size_bytes)
    max_upload_size=50 * 1024 * 1024,
    # Per-file size limit inside the store
    file_store=MemoryFileStore(max_size_bytes=10 * 1024 * 1024),
)
```

| Setting | Default | Enforced by |
|---|---|---|
| `max_upload_files` | `20` | server — returns `400` when exceeded |
| `max_upload_size` | `None` (no cap) | server — returns `413` when exceeded |
| `MemoryFileStore(max_size_bytes=…)` | `10 MiB` | store — returns `413` per file |

### Reading uploaded file contents

Use the `id` from `ctx.event_data["files"][0]["id"]` to build a URL:

```python
async def on_done(ctx: Context):
    files = ctx.event_data.get("files", [])
    for f in files:
        file_url = f"/api/file/{f['id']}"   # served by Refast automatically
        ctx.state.set("url", file_url)
    await ctx.refresh()
```

The URL is served by Refast with the correct `Content-Type` header. Use it in an
`Image` component or any other place that accepts a URL.

### Live Demo — Programmatic Download

Generates a CSV in memory and triggers a browser download.

## ctx.create_file_url()

Register in-memory bytes as a temporary file that can be downloaded or displayed inline.

```python
url = await ctx.create_file_url(
    data,             # bytes
    filename,         # str — suggested download filename
    content_type,     # str — MIME type, e.g. "text/csv", "application/pdf"
    inline=False,     # True → Content-Disposition: inline (for display, not download)
)
```

The URL is scoped to the current session and cleaned up automatically after a short TTL.

### Example — generate and download a CSV

```python
import csv, io
from datetime import datetime

async def download_report(ctx: Context):
    buf = io.StringIO()
    writer = csv.DictWriter(buf, fieldnames=["Name", "Score"])
    writer.writeheader()
    writer.writerows([{"Name": "Alice", "Score": 95}, {"Name": "Bob", "Score": 82}])

    filename = f"report_{datetime.now().strftime('%Y%m%d')}.csv"
    url = await ctx.create_file_url(buf.getvalue().encode(), filename, "text/csv")
    await ctx.trigger_download(url, filename)
```

## ctx.trigger_download()

Instruct the browser to download a URL as a file. Works with any URL — including
ones created with `ctx.create_file_url()`.

```python
await ctx.trigger_download(
    url,       # str — the URL to download
    filename,  # str — the filename that will appear in the browser's download dialog
)
```

### Supported file types

Any MIME type that `bytes` can represent works: CSV, JSON, PDF, images, ZIP archives, etc.

```python
# PDF
url = await ctx.create_file_url(pdf_bytes, "report.pdf", "application/pdf")

# JSON
import json
url = await ctx.create_file_url(
    json.dumps(data).encode(), "data.json", "application/json"
)

# ZIP
url = await ctx.create_file_url(zip_bytes, "export.zip", "application/zip")
```

### Live Demo — Inline File URL

Generates SVG bytes on the server and displays them inline without triggering a download.

## Inline display (no download prompt)

Pass `inline=True` to `ctx.create_file_url()` to get a URL you can use directly as
an image `src` or link `href` without triggering a browser download dialog.

```python
async def show_generated_image(ctx: Context):
    png_bytes = render_chart_to_png(...)  # your rendering logic
    url = await ctx.create_file_url(png_bytes, "chart.png", "image/png", inline=True)
    ctx.state.set("chart_url", url)
    await ctx.refresh()

# In the page renderer:
Image(src=ctx.state.get("chart_url", ""), alt="Generated chart")
```

| `inline` | `Content-Disposition` | Use case |
|---|---|---|
| `False` (default) | `attachment` | Browser download dialog |
| `True` | `inline` | Display in `<img>`, `<a>`, etc. |

## See Also

- [DOM Updates](https://refast.fastapicloud.dev/docs/concepts/updates) — Other ways to update the UI
- [Streaming](https://refast.fastapicloud.dev/docs/concepts/streaming) — Incremental content delivery
- [Form Inputs](https://refast.fastapicloud.dev/docs/components/input) — Other input components

---

Part of the Refast documentation: [all pages](https://refast.fastapicloud.dev/llms.txt), [everything on one page](https://refast.fastapicloud.dev/llms-full.txt), [search](https://refast.fastapicloud.dev/api/search?q=save_prop).
