---
url: /runcobo/guide/uploads.md
description: >-
  Accept multipart file uploads, control request body size, and keep temporary
  files under control.
---

# Request Bodies & Uploads

## Body size limit

Runcobo reads at most **1 MiB** of a request body by default. Larger bodies are rejected with `413` and a `body_too_large` error — whether or not the client sent a `Content-Length`, and before the excess is buffered.

Change the limit per action (or in a base class) by overriding `max_request_body_size`:

```crystal
class Imports::Create < Blog::BaseAction
  post "/imports"

  def max_request_body_size : Int64
    50_i64 * 1024 * 1024   # 50 MiB
  end

  call do
    input = validate(AttachmentContract)
    # ...
  end
end
```

Bodies are read lazily: an action that never touches the body never pays for it. Contracts, `validate`, `raw_body` and `upload` all share one cached read.

## Uploading files

Send files as `multipart/form-data`. In the action, fetch them by field name:

```crystal
class Avatars::Create < Blog::BaseAction
  post "/avatar"

  call do
    file = upload("avatar")   # exactly one file is required
    file.filename             # => "me.png" (as sent by the client)
    file.content_type         # => "image/png" (as sent by the client)
    file.size                 # => 48213 (bytes actually received)

    file.save("storage/avatars/#{UUID.random}.png")
    render_json({size: file.size}, status_code: 201)
  end
end
```

```sh
curl -F "avatar=@me.png" localhost:3000/avatar
```

| Method | Returns | Fails when |
| --- | --- | --- |
| `upload(name)` | One `Runcobo::UploadFile` | No file (`missing`), several files (`multiple_values`), or the field is a plain text field (`invalid_type`) |
| `uploads(name)` | `Array(Runcobo::UploadFile)`, possibly empty | The field is a plain text field |

Failures are reported as normal validation errors with `"source": "file"` and status `422`.

A file input the user left empty — browsers send it with an empty filename and no content — is treated as absent.

### Files and fields together

Validate the text fields of a multipart form with a contract, and fetch the files with `upload`:

```crystal
class AttachmentContract < RequestValidation::Contract
  schema do
    required :title, String, filled: true
    optional :tags, Array(String)
  end
end

class Posts::AttachFile < Blog::BaseAction
  post "/posts/:id/attachments"

  call do
    input = validate(AttachmentContract)
    file = upload("file")
    path = "storage/attachments/#{UUID.random}#{File.extname(file.filename)}"
    file.save(path)
    render_json({title: input.title, tags: input.tags, path: path}, status_code: 201)
  end
end
```

```sh
curl -F title="Q3 report" -F tags=finance -F tags=q3 -F file=@report.pdf localhost:3000/posts/1/attachments
```

### `UploadFile`

| Member | Description |
| --- | --- |
| `filename` | Client-provided name. **Never trust it** as a path. |
| `content_type` | Client-provided type, `application/octet-stream` if absent. Don't trust it for security decisions. |
| `size` | Bytes received |
| `file` | The open temporary `File`, e.g. to stream it to object storage |
| `save(path)` | Atomically copies the upload to `path` (written to a temp file in the same directory, then renamed) |

::: warning Temporary files are deleted after the request
Uploads are stored in temporary files that Runcobo deletes when the request ends — after success, errors, or an early `byebye`. Call `save` (or finish reading `file`) inside the action.
:::

### Limits

Besides the byte limit, a single request may contain at most **100 files** and **1,000 form fields**. Exceeding either returns `413` with `too_many_files` or `too_many_fields`. A malformed multipart body returns `400` with `invalid_multipart`.

### Authenticate first

Use a `before` filter for authentication on upload endpoints. It runs before the multipart body is parsed, so unauthenticated clients can't make your server write temporary files:

```crystal
class Avatars::Create < Blog::BaseAction
  post "/avatar"
  before authenticate
  # ...
end
```

## Reading the raw body

`raw_body` returns the body as a `String` once it has been read and `nil` otherwise. `Blog::BaseAction` reads the body up front with [`read_input`](#checking-the-body-early), so a filter declared in the action can check a webhook signature before `call` runs:

```crystal
require "openssl/hmac"
require "crypto/subtle"

class Webhooks::Payments < Blog::BaseAction
  post "/webhooks/payments"
  before verify_signature

  private def verify_signature
    expected = OpenSSL::HMAC.hexdigest(:sha256, ENV["WEBHOOK_SECRET"], raw_body.not_nil!)
    given = request.headers["X-Signature"]? || ""
    unless Crypto::Subtle.constant_time_compare(expected, given)
      render_plain "invalid signature", status_code: 400
      return byebye
    end
  end

  call do
    input = validate(PaymentEventContract)
    # ...
  end
end
```

Multipart bodies are streamed to temporary files and are never cached as a string, so `raw_body` stays `nil` for them.

## Checking the body early

The body is read the first time something needs it — `validate`, `upload` or `raw_body`. The built-in `read_input` filter reads it up front instead, so the size limit and media type are enforced before any action code runs. `Blog::BaseAction` adds it after authentication:

```crystal [src/actions/base_action.cr]
abstract class Blog::BaseAction < ::BaseAction
  before authenticate
  before read_input   # 413 / 415 / 400 before call runs
end
```

Authentication comes first, so an unauthenticated client can't make the server read a large body.

## Media types

| Body type | `Content-Type` |
| --- | --- |
| JSON | `application/json`, or any `application/*+json` such as `application/vnd.api+json` |
| Form | `application/x-www-form-urlencoded` |
| Multipart | `multipart/form-data; boundary=...` |

Parameters like `; charset=utf-8` are ignored, and matching is case-insensitive. A request whose body doesn't match the declared contract gets `415 unsupported_media_type`.
