@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
231 lines (179 loc) • 10.7 kB
Markdown
---
name: file-uploads
description: >-
Upload files from a form or edit view: useFileUpload from /sdk, with
progress, cancel and isUploading to hold the submit, and initialAttachments
for an edit form; upload from /sdk/server for a server-side upload.
metadata:
type: sub-skill
library: softr-sdk
library_version: 1.19.0
---
**Boundary.** `upload` lives on `/sdk/server` and runs inside server functions. `useFileUpload` and `FileItem` live on `/sdk` and run in components. `FileAttachment` comes from `@softr/sdk` and can be imported anywhere.
# File uploads
`useFileUpload` handles the full upload cycle — XHR with real progress, per-upload cancel, and state management. It uses a server function the SDK registers itself, so no route file is needed in the app.
## Setup
```ts
import { z } from 'zod'
import { defineMutation, type FileAttachment, useFileUpload, type FileItem } from '@softr/sdk'
import { ds } from '@softr/sdk/server'
```
## Core pattern
```ts
const createApplication = defineMutation({
id: 'createApplication',
datasourceId: '8f14e45f-ceea-467a-9d0b-2c1a0e3b5d77',
operation: 'create',
fields: { name: 'V1StGXR8', resume: 'Z7pQm4Kd' },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'] },
})
const submitApplication = createServerFn({ method: 'POST' })
.validator(
z.object({
name: z.string(),
// Zod drops a field the schema leaves out. `.nullish()` is how a record's attachment reads.
resume: z.array(z.object({ url: z.string(), filename: z.string().nullish(), id: z.string().nullish(), type: z.string().nullish() })),
}),
)
.handler(async ({ data }) => {
await ds.create(createApplication, { data: { name: data.name, resume: data.resume } })
})
function ApplicationForm() {
const { files, isUploading, upload, remove } = useFileUpload(createApplication)
return (
<form onSubmit={async (e) => {
e.preventDefault()
if (isUploading) return
const resume = files.filter(f => f.status === 'done')
const name = String(new FormData(e.currentTarget).get('name') ?? '')
await submitApplication({ data: { name, resume } })
}}>
<input name="name" />
<input type="file" onChange={(e) => { const f = e.target.files?.[0]; if (f) upload(f) }} />
{files.map((f) => (
<div key={f.id}>
{f.filename}
{f.status === 'uploading' && <> — {f.progress}% <button type="button" onClick={f.cancel}>Cancel</button></>}
{f.status === 'done' && <button type="button" onClick={() => remove(f.id)}>Remove</button>}
{f.status === 'error' && <span> — Failed: {f.error.message}</span>}
</div>
))}
<button type="submit" disabled={isUploading}>Submit</button>
</form>
)
}
```
`useFileUpload` takes the same `DatasourceAction` you pass to `ds.create` / `ds.update` — no separate upload action to declare.
## What `FileAttachment` looks like
```ts
type FileAttachment = {
url: string // clean URL, no internal query params
filename: string // original filename
id: string // file id extracted from the upload response
type?: string | null // content type from the upload response, or null when the platform doesn't know it
}
```
## Attachment shapes: read, upload and write
An attachment value has three shapes, and none of them is the other:
| Where the value comes from | Its shape |
| --- | --- |
| A record you read, `record.fields.photo` | `{ id, filename, type, url, expiresAt }` plus optional `size` and `thumbnails`. `id`, `filename` and `type` can each be `null` |
| An upload: a `done` item of `useFileUpload`, or what `upload` returns | `FileAttachment`: `url`, `filename` and `id` are strings |
| A write, the `data` of `ds.create` / `ds.update` | `{ url }`, optionally with `filename`, `id` and `type` |
Whether the field holds one file or several decides the rest. `docs/datasources/` types a one-file field `ATTACHMENT` and a several-file field `ATTACHMENT[]`.
- A one-file field reads one attachment or `null`, never an array. Its write takes one object, or `null` to clear it. Never index it with `[0]`, and never wrap it in an array.
- A several-file field reads an array, and its write takes an array.
- A read attachment and a `FileAttachment` are both valid write values as they are. Copying a file from one record to another needs no mapping.
- A function or schema of your own that takes attachments types `filename`, `id` and `type` as `string | null`, the way a record reads them; in zod that is `.nullish()`, not `.optional()`. A parameter typed `filename: string` refuses every attachment a record reads, and a `type` that is only optional refuses an uploaded `FileAttachment`.
- `initialAttachments` takes `FileAttachment[]`, which a read attachment is not. Map it first, as the edit form below does.
## FileItem shape
`files` is a single ordered array. Each entry is a discriminated union on `status`:
```ts
type FileItem =
| { status: 'uploading'; id: string; filename: string; progress: number; cancel: () => void }
| (FileAttachment & { status: 'done' })
| { status: 'error'; id: string; filename: string; error: Error }
```
Items appear in insertion order and transition in place — a completed upload stays at its original position rather than moving to a separate list.
For form submission, filter to `done` items: `files.filter(f => f.status === 'done')` is a `FileAttachment[]` with no cast. A one-file field sends the first of them, `done[0] ?? null`, not the array.
## Blocking form submission
`isUploading` is `true` while any item has `status: 'uploading'`. Disable the submit button and guard the submit handler.
## Edit forms: pre-loading existing attachments
A record's attachments can have a `null` id or filename, and `initialAttachments` wants strings, so map each one to a `FileAttachment` first. The upload control tells its files apart by id, so a file without one takes its url as id: two files sharing `''` would be removed together. `ds` runs only on the server, so the page loads and saves the record through server functions. Here `resume` holds several files and `photo` holds one:
```tsx
const loadApplication = createServerFn({ method: 'GET' })
.validator((id: string) => id)
.handler(async ({ data: id }) => {
const record = await ds.get(applicationDetail, { id })
if (!record) throw notFound()
return record
})
const Attachment = z.object({ url: z.string(), filename: z.string().nullish(), id: z.string().nullish(), type: z.string().nullish() })
const saveApplication = createServerFn({ method: 'POST' })
.validator(z.object({ id: z.string(), resume: z.array(Attachment), photo: Attachment.nullable() }))
.handler(async ({ data }) => {
await ds.update(updateApplication, { id: data.id, data: { resume: data.resume, photo: data.photo } })
})
export const Route = createFileRoute('/_app/applications/$id')({
loader: ({ params }) => loadApplication({ data: params.id }),
component: EditApplication,
})
type ReadFile = { url: string; filename: string | null; id: string | null }
function filesOf(files: ReadFile[] | null): FileAttachment[] {
return (files ?? []).map((file) => ({ url: file.url, filename: file.filename ?? '', id: file.id ?? file.url }))
}
function EditApplication() {
const record = Route.useLoaderData()
const resume = useFileUpload(updateApplication, { initialAttachments: filesOf(record.fields.resume) })
const photo = useFileUpload(updateApplication, {
initialAttachments: filesOf(record.fields.photo === null ? null : [record.fields.photo]),
})
// the several-file field sends every done file, the one-file field its first or null
async function save() {
const photoFiles = photo.files.filter((f) => f.status === 'done')
const resumeFiles = resume.files.filter((f) => f.status === 'done')
await saveApplication({ data: { id: record.id, resume: resumeFiles, photo: photoFiles[0] ?? null } })
}
// render resume.files and photo.files as in the core pattern above
return (
<button type="button" disabled={resume.isUploading || photo.isUploading} onClick={() => void save()}>
Save
</button>
)
}
```
Pre-loaded attachments appear as `status: 'done'` items at the start of `files`.
## Server-side uploads and plain forms
For server-side use (no progress tracking needed) or plain HTML forms, use `upload` directly:
```ts
import { z } from 'zod'
import { upload, ds } from '@softr/sdk/server'
const Application = z.object({ fullName: z.string().min(1), cv: z.instanceof(File) })
const submitResume = createServerFn({ method: 'POST' })
.validator((fields: FormData) => Application.parse({ fullName: fields.get('fullName'), cv: fields.get('cv') }))
.handler(async ({ data }) => {
const uploaded = await upload(createApplication, data.cv)
await ds.create(createApplication, {
data: { fullName: data.fullName, cv: [uploaded] }, // cv holds several files; a one-file field takes `uploaded` itself
})
return new Response(null, { status: 303, headers: { Location: '/thank-you' } })
})
function ApplyForm() {
return (
<form action={submitResume.url} method="POST">
<input type="text" name="fullName" />
<input type="file" name="cv" />
<button type="submit">Apply for this role</button>
</form>
)
}
```
## Failure modes
**Submitting while `isUploading` is true.** Only `done` items have a `url` and should be submitted. In-progress uploads finish after the record is saved and are never included. Always filter to `status === 'done'` before passing to `ds.create` / `ds.update`.
**Not passing `initialAttachments` on an edit form.** The hook starts with an empty list. Without pre-loading, the first save erases existing attachments.
**Passing a record's attachments straight to `initialAttachments`.** Their `id` and `filename` can be `null`, and `FileAttachment` wants strings, so type-checking refuses them. Map them with `filesOf` as in the edit form above.
**Filling every missing attachment id with `''`.** Files that share an id are one file to the upload control: removing one removes them all, and the save drops them.
**Treating a one-file field as an array.** A one-file field reads one attachment or `null` and writes one object or `null`. Indexing it with `[0]`, or writing `[file]` or the whole `done` list to it, fails type-checking.
## References
- [record-mutations/SKILL.md](../record-mutations/SKILL.md): creating and updating records with the collected attachments
- [current-user/SKILL.md](../current-user/SKILL.md): gating uploads to the signed-in user