UNPKG

@rsc-kit/mcp

Version:

An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.

216 lines (150 loc) • 5.46 kB
# File uploads > Sending files through a server action without encoding them. A server action can take a `File` as an argument. It travels as binary, so there is nothing to encode in the browser and nothing to decode on the server: ```ts title="src/actions.ts" 'use server' export async function uploadAvatar(file: File) { console.log(file.name, file.type, file.size) } ``` It is the same call and the same round trip as [any other server action](/guides/server-actions). ## Uploading one file Read the file from the form in a client component and pass it to the action: ```tsx title="src/components/AvatarUpload.tsx" "use client"; import { useState } from 'react'; import { uploadAvatar } from '../actions'; export function AvatarUpload() { const [url, setUrl] = useState<string | null>(null); async function submit(formData: FormData) { const file = formData.get('avatar') as File; if (!file || file.size === 0) return; setUrl(await uploadAvatar(file)); } return ( <form action={submit}> <input type="file" name="avatar" accept="image/*" /> <button type="submit">Upload</button> {url && <img src={url} alt="" />} </form> ); } ``` The action receives the `File` itself, with its name, type and size: ```ts title="src/actions.ts" 'use server' import { writeFile } from 'node:fs/promises'; const extensions: Record<string, string> = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' }; export async function uploadAvatar(file: File): Promise<string> { const extension = extensions[file.type]; if (!extension) throw new Error('Not an image this app stores.'); const name = `${crypto.randomUUID()}.${extension}`; await writeFile(`./public/avatars/${name}`, new Uint8Array(await file.arrayBuffer())); return `/avatars/${name}`; } ``` Name the stored file yourself. `file.name` comes from the visitor's computer and can be anything, `../` included. So can `file.type`: it is what the browser said, so take the extension from a list of your own, never from the type's text. ## Sending the whole form An action can take the `FormData` instead. That is simpler when the form mixes files and fields: ```tsx "use client"; import { createPost } from '../actions'; export function NewPost() { return ( <form action={createPost}> <input name="title" /> <textarea name="body" /> <input type="file" name="cover" accept="image/*" /> <button type="submit">Create</button> </form> ); } ``` ```ts title="src/actions.ts" 'use server' export async function createPost(formData: FormData) { const title = formData.get('title') as string; const cover = formData.get('cover') as File; // … } ``` ## Uploading several files `formData.getAll` returns every file from a `multiple` input, and an array of `File` travels as easily as one: ```tsx <input type="file" name="photos" accept="image/*" multiple /> ``` ```tsx const files = formData.getAll('photos') as File[]; await uploadPhotos(files); ``` ```ts title="src/actions.ts" 'use server' export async function uploadPhotos(files: File[]) { for (const file of files) { // … } } ``` ## Checking the file `accept` only filters the browser's file picker. Check the type and size in the action, where it can't be skipped: ```ts title="src/actions.ts" 'use server' const allowed = ['image/png', 'image/jpeg', 'image/webp']; export async function uploadAvatar(file: File) { if (!allowed.includes(file.type)) { return { error: 'Choose a PNG, JPEG or WebP image.' }; } if (file.size > 2 * 1024 * 1024) { return { error: 'The image must be under 2 MB.' }; } // store it … } ``` `file.type` is the sender's claim, not a fact about the bytes: a script can post HTML and call it `image/png`. Where the file is served back to other visitors, read its first bytes and compare them with the type's signature, and serve uploads with `X-Content-Type-Options: nosniff`. [Validation](/guides/validation) covers showing errors like these beside the field. ## Raising the size limit The server refuses a body over **8 MB** with a 413, before it holds a byte of it, and the form reports a failed submission. Raise the limit when the app uploads more: ```ts title="vite.config.ts" rscKit({ maxActionBody: 32 * 1024 * 1024 }) ``` The whole body is held in memory before the action runs: it is one `POST`, not a stream. Keep the limit, and any limit a proxy in front sets, as low as the app needs. ## Uploading large files to storage For large files, skip the action for the bytes. The action hands out a pre-signed URL, and the browser uploads straight to storage: ```ts title="src/actions.ts" 'use server' import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; const s3 = new S3Client({}); export async function uploadUrl(type: string) { const key = `videos/${crypto.randomUUID()}`; const url = await getSignedUrl(s3, new PutObjectCommand({ Bucket: 'uploads', Key: key, ContentType: type }), { expiresIn: 300 }); return { key, url }; } ``` ```tsx "use client"; import { uploadUrl } from '../actions'; async function upload(file: File) { const { key, url } = await uploadUrl(file.type); await fetch(url, { method: 'PUT', body: file, headers: { 'Content-Type': file.type } }); return key; } ``` The bytes never touch your server, so the size limit doesn't apply.