Course contentsShow
← React
Lesson 1620 of 2,39639. Server Components in PracticeFree lesson

File Uploads with Server Actions

Handling file inputs and multipart form data in server actions for image and document uploads.

File Uploads with Server Actions

You'll learn how to handle file uploads directly in server actions using native FormData, without needing separate API routes or file upload libraries.

The Core Idea

File uploads are just another form of data submission, but they use multipart/form-data encoding. Server actions automatically handle this when you use <input type="file"> in your form. The file arrives as a File object in the FormData, which you can read, validate, and save on the server.

How It Works

When a user selects a file and submits a form, the browser sends it as part of the form submission. In your server action, you extract the file from FormData just like any other field:

'use server'

async function uploadImage(formData: FormData) {
  const file = formData.get('avatar') as File
  
  if (!file || file.size === 0) {
    return { error: 'No file selected' }
  }

  // Validate file type and size
  if (!file.type.startsWith('image/')) {
    return { error: 'Must be an image file' }
  }

  if (file.size > 5 * 1024 * 1024) { // 5MB
    return { error: 'File too large' }
  }

  // Read file contents
  const bytes = await file.arrayBuffer()
  const buffer = Buffer.from(bytes)

  // Save to filesystem, cloud storage, etc.
  // await saveFile(buffer, file.name)

  return { success: true }
}

Your form needs the proper input type and name attribute:

<form action={uploadImage}>
  <input type="file" name="avatar" accept="image/*" />
  <button type="submit">Upload</button>
</form>

Key Takeaway: Server actions handle file uploads through standard FormData—extract files with formData.get(), validate size and type on the server, then process the file buffer for storage. Always validate uploads server-side for security.