Upload files
Upload files with a typed multipart body.
Upload files with a body that's typed and checked by a schema, as for JSON,
then sent as multipart/form-data.
Send a multipart body
To upload files, wrap the input schema in Fetch.multipart, and use
Fetch.UploadFile for a file field:
import * as from "effect/Effect";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
const = .({ : . });
export const = .("POST /documents", {
: .(
.({
: .,
: .(["PASSPORT", "DRIVERS_LICENSE"]),
: .(.),
}),
),
: ,
});
class extends .<>()("Api", {
: "https://api.example.com",
}) {}
class extends .<>()("DocumentApi", , {
: ,
}) {}
// In a browser, `file` comes from an <input type="file">.
export const = (: ) =>
.(function* () {
const = yield* ;
return yield* .({ : { , : "PASSPORT" } });
});Files on each platform
Fetch.UploadFile takes the files each platform can send:
- in browsers, Node, Bun and Deno, a
BloborFile; - in React Native, the
{ uri, name, type }object its pickers give, typedFetch.NativeFile.uriandnameare required: 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 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
Effetch turns the schema's fields into form parts as follows:
- strings as they are; numbers, booleans and bigints as strings; a
Dateas its ISO string; - a file as a file part;
- a list as one part per item, under the same name;
nullandundefinedleft 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
The following details cover the request's headers, how a bad body fails, and where multipart bodies work.
- The request sets no
Content-Type, so the platform adds the multipart boundary. Acontent-typeheader from the call, the endpoint or the client is removed, for anyFormDatabody. - The request sets no
Content-Typebefore your plugins run. A plugin'sonRequestthat sets one replaces 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, as for JSON (see Logging and defects). So does a{ uri, name, type }file outside React Native, whereFormDatawould send"[object Object]", or in a field that isn't aFetch.UploadFile. Fetch.UploadFilein aninputschema withoutFetch.multipartmakes the call die too: a file has no JSON form.- 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 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. FetchTestreads the form back into the body a handler gets, decoded with the schema, with files asFiles. In Node, 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
- A
FormDatayou build yourself still works as abodywithoutinput.
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.