| | |

SvelteKit Forms 10 ๐Ÿ“ File Uploads & filesProxy() โ€” Validating file sizes/MIME types with Zod, handling multipart/form-data, and preserving file inputs

โฑ๏ธ Estimated read: 7 min | |

Handling file uploads in web forms introduces a significant shift in how data is processed. Unlike standard text fields that exist as JSON-serializable primitives, files are binary blobs that require specific handling via multipart/form-data. Integrating these into a reactive framework like SvelteKit requires careful synchronization between the browser’s file input state and the server-side validation logic. Superforms simplifies this with the filesProxy() utility, which allows you to bind file inputs to your form stores while maintaining the full suite of validation capabilities.

This chapter explores how to configure forms to support binary uploads, how to define Zod schemas that enforce file size and MIME type restrictions, and how to manage the lifecycle of a file inputโ€”from user selection to successful server-side processing.

Key point: File uploads require enctype="multipart/form-data" on your form and the use of the filesProxy() utility; Zod validation ensures that only files meeting specific criteriaโ€”such as size or content typeโ€”are ever processed by your server-side actions.


Why exists

The binary transmission challenge. Native browser form submission handles files differently than text, requiring the multipart/form-data encoding. Without this, your server cannot distinguish between the binary stream and the rest of the formโ€™s metadata.

The client-side validation gap. Relying solely on server-side validation for files leads to a poor user experience, as users may wait for a large upload to finish before discovering the file is too big or the wrong type. Client-side checks are necessary for instant feedback.

The file input state problem. HTML file inputs are “read-only” in many contextsโ€”you cannot bind value in the traditional sense because browsers protect the local file path. filesProxy() acts as the necessary bridge to track these binary inputs reactively within the form state.

The schema enforcement need. Zod is excellent for strings, but verifying a file’s integrity requires checking instances and metadata properties. Standardizing this within your existing form validation logic keeps your server code DRY and secure.

The security boundary. Uploading files is a high-risk operation. By centralizing the validation logic within a Zod schema, you ensure that every upload is sanitized and verified before your action code ever touches the file contents.


a. Linking file inputs with filesProxy()

The filesProxy() helper is essential because you cannot bind value to a file input for security reasons. Instead, you create a proxy that links the file input to your form store. When the user selects a file, the proxy updates the store, allowing you to trigger validation based on the file’s metadata.

const { form } = superForm(data.form);
const files = filesProxy(form, 'image'); // Link to 'image' field in schema

<input 
  type="file" 
  accept="image/png, image/jpeg" 
  onchange={(e) => $files = e.target.files} 
/>

When the user selects a file, the proxy stores the FileList object in your form state. This allows Svelte Query to see that the field is no longer empty, enabling validation and submission tracking as if it were any other form input.


b. Validating binary data with Zod

Validation for files uses Zodโ€™s instanceof(File) check. You can extend this to check for size (in bytes) or type (MIME type). Because this validation runs during the superValidate phase on the server, it provides a final, mandatory line of defense for your applicationโ€™s storage layer.

const schema = z.object({
  image: z.instanceof(File, { message: "Please upload a file" })
    .refine((f) => f.size < 5000000, "Max 5MB upload")
    .refine((f) => f.type.startsWith('image/'), "Only images allowed")
});

By defining these refinements, you ensure that the server rejects invalid uploads immediately. When coupled with the client-side accept attribute on the input, you create a cohesive feedback loop that guides the user toward successful uploads while protecting your infrastructure.


c. Multipart handling and action setup

Because file inputs require multipart/form-data, you must ensure your server-side action and form element are configured correctly. Superforms automatically detects the form type, but you must ensure your Zod schema and server validation are aware that the incoming data contains binary blobs.

// +page.server.ts
export const actions = {
  default: async ({ request }) => {
    const formData = await request.formData();
    const form = await superValidate(formData, zod(schema));
  
    if (!form.valid) return fail(400, { form });
    // Process form.data.image ...
  }
};

On the client side, ensure your <form> element has the enctype="multipart/form-data" attribute. Without this, the browser will strip the binary data, and your server will receive an empty object instead of the actual file.


Complete Example Session

// ============================================
// PART 1: ZOD SCHEMA WITH VALIDATION
// ============================================
const schema = z.object({
  avatar: z.instanceof(File)
    .refine(f => f.size < 2000000, 'Must be < 2MB')
});

// ============================================
// PART 2: FORM SETUP
// ============================================
const { form, enhance } = superForm(data.form);
const files = filesProxy(form, 'avatar');

// ============================================
// PART 3: UI BINDING
// ============================================
<form method="POST" enctype="multipart/form-data" use:enhance>
  <input type="file" onchange={(e) => $files = e.target.files} />
  {#if $errors.avatar} <p>{$errors.avatar}</p> {/if}
  <button>Upload</button>
</form>

// ============================================
// PART 4: SERVER PROCESSING
// ============================================
// Inside action:
const file = form.data.avatar;
const buffer = await file.arrayBuffer();

The sequence shows defining strict file constraints, binding inputs to a proxy store, configuring the form for binary encoding, and accessing the raw binary data on the server.


Quick Reference

File Validation

HelperPurpose
z.instanceof(File)Type enforcement
.refine(f => f.size < N)Size enforcement
.refine(f => f.type === M)MIME enforcement

Multipart Essentials

RequirementPurpose
enctype="multipart/form-data"Enables binary transmission
filesProxy()Reactive file state binding
request.formData()Server-side parsing

Best Practices

โœ… Do This:

// Always specify MIME types in the input
<input type="file" accept="image/*" />                       // โœ…

// Validate file size in Zod schema
z.instanceof(File).refine(f => f.size < MAX)                 // โœ…

// Set enctype on the form tag
<form enctype="multipart/form-data">                         // โœ…

// Handle the arrayBuffer on the server
await file.arrayBuffer();                                    // โœ…

โŒ Don’t Do This:

// Don't use standard JSON for files
// (Multipart is required)                                   // โŒ

// Don't trust client-side validation alone
// (Server-side validation is mandatory)                     // โŒ

// Don't bind value to file input
// (Use filesProxy and onChange)                             // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Empty payloadMissing enctypeAdd enctype="multipart/form-data"
State sync failBinding value to file inputUse filesProxy + onchange
Security riskAccepting all MIME typesFilter by type in Zod
Memory bloatLoading massive filesValidate size before processing

Real-World Examples

1. Image Upload

z.instanceof(File).refine(f => f.type.includes('image'))

2. Size Enforcement (5MB)

f.size < 5 * 1024 * 1024

3. Proxy Usage

const avatar = filesProxy(form, 'avatar')

4. MIME type check

f.type === 'application/pdf'

5. Server reading

const buffer = Buffer.from(await file.arrayBuffer())

6. Required File

z.instanceof(File).refine(f => f.size > 0)

7. Input Accept Attribute

<input accept=".pdf,.png" />

8. Submission status

disabled={$submitting}

9. Error display

{$errors.avatar}

10. Form configuration

use:enhance={{ formAction: '/upload' }}

Visual

The Binary Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  INPUT(file) โ”€โ”€โ–บ filesProxy() (Reactive)     โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚  ENCTYPE="multipart/form-data"               โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚  SERVER: superValidate(formData)             โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚  ZOD: Refine(size, type) โ”€โ”€โ–บ Valid/Invalid   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Client to Server lifecycle

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Browser: FormData construction              โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚  Transport: Binary blob attached             โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚  Server: Parsing stream to Buffer            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Encodingmultipart/form-data
ProxyfilesProxy()
Type Checkz.instanceof(File)
Bufferawait file.arrayBuffer()

Key takeaways:

  • Multipart is non-optional. You must define enctype="multipart/form-data" on your form element, or the binary data will never reach your server.
  • Always use filesProxy(). It is the standard way to handle the disconnected nature of file inputs and keep your reactive state accurate.
  • Validate aggressively. File uploads are a primary vector for attacks; use Zod to strictly enforce size and MIME types on the server side.
  • Client-side is for UX. Use the accept attribute and client-side Zod validation to give the user immediate feedback, but remember the server is the source of truth.
  • Buffer safely. Files arrive as blobs; always transform them into usable binary formats (arrayBuffer or Buffer) before passing them to storage services or database operations.

Remember: File uploads bridge the gap between simple form interaction and infrastructure management. By using the specialized tools in Superforms and Zod, you ensure that this complex operation remains as safe, predictable, and maintainable as any other text field in your application.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!