# Upload files (https://effetch.pages.dev/docs/calls/uploads)

Most APIs take a file upload as a `multipart/form-data` body: the file in
one part, and the other fields in parts beside it. Effetch builds that form
from a schema, so an upload's body is typed and checked the way a JSON body
is. This page shows how to send one, how each platform passes its files,
and how the schema's fields become form parts.

## Send a multipart body

To upload files, wrap the `input` schema in `Fetch.multipart`, and use
`Fetch.UploadFile` for each file field:

```ts
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";

declare const api: Fetch.Client;

const Document = Schema.Struct({ id: Schema.String });

const NewDocument = Fetch.multipart(
  Schema.Struct({
    file: Fetch.UploadFile,
    kind: Schema.Literals(["PASSPORT", "DRIVERS_LICENSE"]),
    pages: Schema.optional(Schema.Finite),
  }),
);

// In a browser, `file` comes from an <input type="file">.
export const upload = (file: File) =>
  api.post("/documents", {
    input: NewDocument,
    body: { file, kind: "PASSPORT" },
    output: Document,
  });
```

`Fetch.multipart` marks the schema, so the body is encoded with it and then
sent as a form rather than as JSON. TypeScript checks `body` against the
schema, as it does for any `input`.

The same schema works in an endpoint definition (see
[Endpoints or methods](https://effetch.pages.dev/docs/endpoints)), so the upload's route and schemas live in one
place:

```ts
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";

declare const api: Fetch.Client;

export const uploadDocument = Fetch.endpoint("POST /documents", {
  input: Fetch.multipart(
    Schema.Struct({
      file: Fetch.UploadFile,
      kind: Schema.Literals(["PASSPORT", "DRIVERS_LICENSE"]),
    }),
  ),
  output: Schema.Struct({ id: Schema.String }),
});

const send = api.bind(uploadDocument);

export const upload = (file: File) =>
  send({ body: { file, kind: "PASSPORT" } });
```

## Files on each platform

A file field takes the kind of file each platform can send. That differs
between platforms, so `Fetch.UploadFile` accepts each of them:

- **In browsers, Node.js, Bun and Deno:** a `Blob` or `File`.
- **In React Native:** the `{ uri, name, type }` object its pickers give,
  typed `Fetch.NativeFile`. `uri` and `name` are required, because a server
  only treats a part as a file when it has a file name. `type` is optional,
  and a file without one is sent as `application/octet-stream`.

Use `Fetch.UploadFile` rather than `Schema.File`. `Schema.File` only takes a
`File`, not the `{ uri, name, type }` objects React Native's pickers give,
and `FetchTest` can't read it back from a form.

## Send a file from React Native

In React Native, send a `NativeFile`, not a `Blob`. React Native's `fetch`
reads a form's files from disk by their `uri`, and can't send a `Blob` in a
form.

The following example builds a `NativeFile` from an image picker's asset:

```ts
import type { Fetch } from "@monarcode/effetch";

// From expo-image-picker, for example
declare const asset: {
  readonly uri: string;
  readonly fileName?: string | null;
  readonly mimeType?: string;
};

export const photo: Fetch.NativeFile = {
  uri: asset.uri,
  name: asset.fileName ?? "photo.jpg",
  type: asset.mimeType,
};
```

## How fields become form parts

A form holds only strings and files, so Effetch encodes the body with the
schema, then turns each field into form parts as follows:

- A string is sent as it is.
- A number, boolean or bigint is sent as a string, and a `Date` as its ISO
  string.
- A file becomes a file part.
- A list becomes one part per item, all under the field's name.
- `null` and `undefined` are left out.

A form can't hold a nested object or a list of lists, so TypeScript rejects
most schemas that have one, and a value that has one makes the call die. To
send one, encode it to a string in the schema, such as
`meta: Schema.fromJsonString(Meta)`.

## Check a file's size

To check a file's size, add a check to `Fetch.UploadFile`. A `NativeFile`
has no size until it's read, so the check only looks at a `Blob`:

```ts
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";

export const SmallFile = Fetch.UploadFile.check(
  Schema.makeFilter(
    (file) => !(file instanceof Blob) || file.size < 10_000_000,
    { expected: "a file under 10 MB" },
  ),
);
```

## Headers, errors and where it works

Most uploads need nothing more than the sections on this page. The
following details cover the request's `content-type`, how a bad body fails, where multipart
bodies work, and how `FetchTest` reads a form back.

**Details: the content-type header**

- Effetch sets no `content-type` on a form, so the platform adds
  `multipart/form-data` with its boundary. A `content-type` from the call,
  the endpoint or the client is removed, as for any `FormData` body (see
  [Set the content type](https://effetch.pages.dev/docs/calls/body#set-the-content-type)).
- That happens before your plugins run. A plugin's `onRequest` that sets a
  `content-type` replaces the boundary, so leave it out for forms.

**Details: bodies that make the call die**

- A body that doesn't match the schema, or a value a form can't hold, makes
  the call die with an `Invalid request body:` defect, the same as a JSON
  body that doesn't match its `input` (see
  [Logging and defects](https://effetch.pages.dev/docs/errors/logging-and-defects)).
- So does a `{ uri, name, type }` file outside React Native, where
  `FormData` would send `"[object Object]"`, or one in a field that isn't a
  `Fetch.UploadFile`.
- `Fetch.UploadFile` in an `input` schema without `Fetch.multipart` makes
  the call die too, since a file has no JSON form.
- A field's encoded value must be a string, number, boolean, bigint,
  `Date`, file, `null` or `undefined`, or a list of them. A schema such as
  `Schema.DateTimeUtc` or `Schema.URL`, which encodes to an object, needs a
  string form first, such as `Schema.DateTimeUtcFromString`.

**Details: where Fetch.multipart works**

- It works wherever `input` does: on methods such as `api.post`, on
  endpoints, and in `api.sse` and `api.ndjson`.
- `Fetch.multipart` returns the schema, marked. Add checks or annotations to
  it as you like. A schema built around it, such as with `Schema.NullOr`, is
  sent as JSON again.
- A `FormData` you build yourself still works as a `body` without `input`
  (see [Send a body](https://effetch.pages.dev/docs/calls/body#send-a-form-text-or-bytes)).

**Details: reading a form back in FetchTest**

- [`FetchTest`](https://effetch.pages.dev/docs/testing) reads the form back into the body a handler
  gets, decoded with the schema, with files as `File`s. In Node.js, test
  with a `Blob` or `File`, since a `{ uri, name, type }` file only works in
  React Native.
- A form loses some of what the schema encodes, so `FetchTest` reads it back
  as best it can:
  - A `null` or `undefined` field and an empty list are left out. Such a
    field comes back missing when it's optional. When it's required, it
    comes back as `null` if it takes `null`, then as `[]` if it's a list,
    then as `undefined`.
  - Every part is a string. In a field that takes `null`, the string
    `"null"` comes back as `null`, and in
    `Schema.Union([Schema.String, Schema.Finite])` the string `"12"` comes
    back as the number `12`.

## What's next

- [Send a body](https://effetch.pages.dev/docs/calls/body): send JSON and other bodies.
- [Test with a fake backend](https://effetch.pages.dev/docs/testing): read uploaded forms back in
  tests with `FetchTest`.
- [Logging and defects](https://effetch.pages.dev/docs/errors/logging-and-defects): see why a bad body
  makes the call die.