Upload files
Upload files with a typed multipart body.
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:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
declare const : .;
const = .({ : . });
const = .(
.({
: .,
: .(["PASSPORT", "DRIVERS_LICENSE"]),
: .(.),
}),
);
// In a browser, `file` comes from an <input type="file">.
export const = (: ) =>
.("/documents", {
: ,
: { , : "PASSPORT" },
: ,
});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), so the upload's route and schemas live in one place:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
declare const : .;
export const = .("POST /documents", {
: .(
.({
: .,
: .(["PASSPORT", "DRIVERS_LICENSE"]),
}),
),
: .({ : . }),
});
const = .();
export const = (: ) =>
({ : { , : "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
BloborFile. - In React Native: the
{ uri, name, type }object its pickers give, typedFetch.NativeFile.uriandnameare required, because a server only treats a part as a file when it has a file name.typeis optional, and a file without one is sent asapplication/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:
import type { } from "@monarcode/effetch";
// From expo-image-picker, for example
declare const : {
readonly : string;
readonly ?: string | null;
readonly ?: string;
};
export const : .NativeFile = {
: .,
: . ?? "photo.jpg",
: .,
};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
Dateas its ISO string. - A file becomes a file part.
- A list becomes one part per item, all under the field's name.
nullandundefinedare 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:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
export const = ..(
.(
() => !( instanceof ) || . < 10_000_000,
{ : "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.
- Effetch sets no
content-typeon a form, so the platform addsmultipart/form-datawith its boundary. Acontent-typefrom the call, the endpoint or the client is removed, as for anyFormDatabody (see Set the content type). - That happens before your plugins run. A plugin's
onRequestthat sets acontent-typereplaces the boundary, so leave it out for forms.
- 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 itsinput(see Logging and defects). - So does a
{ uri, name, type }file outside React Native, whereFormDatawould send"[object Object]", or one in a field that isn't aFetch.UploadFile. Fetch.UploadFilein aninputschema withoutFetch.multipartmakes 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,nullorundefined, or a list of them. A schema such asSchema.DateTimeUtcorSchema.URL, which encodes to an object, needs a string form first, such asSchema.DateTimeUtcFromString.
- It works wherever
inputdoes: on methods such asapi.post, on endpoints, and inapi.sseandapi.ndjson. Fetch.multipartreturns the schema, marked. Add checks or annotations to it as you like. A schema built around it, such as withSchema.NullOr, is sent as JSON again.- A
FormDatayou build yourself still works as abodywithoutinput(see Send a body).
FetchTestreads the form back into the body a handler gets, decoded with the schema, with files asFiles. In Node.js, test with aBloborFile, since a{ uri, name, type }file only works in React Native.- A form loses some of what the schema encodes, so
FetchTestreads it back as best it can:- A
nullorundefinedfield and an empty list are left out. Such a field comes back missing when it's optional. When it's required, it comes back asnullif it takesnull, then as[]if it's a list, then asundefined. - Every part is a string. In a field that takes
null, the string"null"comes back asnull, and inSchema.Union([Schema.String, Schema.Finite])the string"12"comes back as the number12.
- A
What's next
- Send a body: send JSON and other bodies.
- Test with a fake backend: read uploaded forms back in
tests with
FetchTest. - Logging and defects: see why a bad body makes the call die.