πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

File Upload

Next.js Features🟒 Free Lesson

Advertisement

File Upload

Server actions for uploads, S3 integration, image processing, and progress tracking.

Overview

File uploads handle user-generated content in Next.js applications.

Key Concepts

  • Server Actions β€” Handle file uploads
  • S3 Uploads β€” Store files in cloud storage
  • Image Processing β€” Resize and optimize uploads
  • Progress Tracking β€” Show upload progress
  • Validation β€” File type and size validation

Code Examples

// Server action for file upload
'use server';
import { put } from '@vercel/blob';

export async function uploadFile(formData) {
  const file = formData.get('file');
  
  if (!file) {
    return { error: 'No file provided' };
  }

  // Validate file type
  const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
  if (!allowedTypes.includes(file.type)) {
    return { error: 'Invalid file type' };
  }

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

  const blob = await put(file.name, file, {
    access: 'public',
    contentType: file.type
  });

  return { url: blob.url };
}

// Client component with progress
'use client';
import { useState } from 'react';

function FileUpload() {
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setUploading(true);
    
    const formData = new FormData(e.target);
    const result = await uploadFile(formData);
    
    setUploading(false);
    if (result.error) {
      alert(result.error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" name="file" accept="image/*" />
      <button type="submit" disabled={uploading}>
        {uploading ? `Uploading... ${progress}%` : 'Upload'}
      </button>
    </form>
  );
}

Practice

Build a multi-file upload component with drag-and-drop and progress tracking.

⭐

Premium Content

File Upload

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement