📁 File Uploads, Forms & Error Systems

Complete Guide with Interactive Examples

🎯 Introduction

File uploads, forms aur error handling modern web applications ke essential parts hain. Ye features user experience ko better banate hain aur application ko robust banate hain.

Is guide mein hum seekhenge:

  • Single aur multiple file uploads kaise implement karein
  • Drag-and-drop functionality kaise add karein
  • Client-side validation architecture
  • Error boundaries aur error handling best practices

Key Concepts

File Upload: The process of transferring files from a client device to a server through a web application.

Form Validation: The process of ensuring that user input meets specified criteria before submission.

Error Boundary: A React component that catches JavaScript errors anywhere in the child component tree and displays a fallback UI.

Why These Topics Matter

  • User Experience: Smooth file uploads aur clear error messages user satisfaction improve karte hain
  • Data Integrity: Proper validation ensures ki only valid data server tak pahunche
  • Security: Client-side validation first line of defense hai malicious inputs ke against
  • Performance: Client-side validation unnecessary server requests reduce karta hai
  • Reliability: Error boundaries application crashes prevent karte hain

Common Use Cases

📸 Profile Pictures

User profile images upload karna with preview

📄 Document Upload

PDFs, resumes, certificates upload karna

🖼️ Gallery Upload

Multiple images ek saath upload karna

📊 Data Import

CSV, Excel files import karna

📤 File Upload Implementation

File upload implement karna HTML5 ke saath bahut easy ho gaya hai. Hum input type="file" use karte hain aur JavaScript se files ko handle karte hain.

Single File Upload

// HTML <input type="file" id="fileInput" accept="image/*" /> <button onclick="uploadFile()">Upload</button> // JavaScript function uploadFile() { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; if (!file) { alert('Please select a file'); return; } // File validation const maxSize = 5 * 1024 * 1024; // 5MB if (file.size > maxSize) { alert('File size should be less than 5MB'); return; } // Create FormData const formData = new FormData(); formData.append('file', file); // Upload to server fetch('/api/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { console.log('Upload successful:', data); }) .catch(error => { console.error('Upload failed:', error); }); }

Multiple File Upload

// HTML <input type="file" id="multiFileInput" multiple accept="image/*" /> // JavaScript function uploadMultipleFiles() { const fileInput = document.getElementById('multiFileInput'); const files = Array.from(fileInput.files); if (files.length === 0) { alert('Please select files'); return; } const formData = new FormData(); // Append all files files.forEach((file, index) => { formData.append(`file${index}`, file); }); // Upload with progress tracking const xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', (e) => { if (e.lengthComputable) { const percentComplete = (e.loaded / e.total) * 100; console.log(`Upload progress: ${percentComplete}%`); } }); xhr.addEventListener('load', () => { if (xhr.status === 200) { console.log('Upload successful'); } }); xhr.open('POST', '/api/upload-multiple'); xhr.send(formData); }

Interactive Demo: File Upload

🎮 Try File Upload
✅ Files uploaded successfully!

⚠️ Important Points

  • File Size Limits: Always validate file size client-side aur server-side dono pe
  • File Types: Accept attribute se allowed file types specify karein
  • Security: Server-side validation mandatory hai, client-side bypass ho sakta hai
  • Progress Tracking: Large files ke liye progress indicator show karein

React Implementation

import { useState } from 'react'; function FileUpload() { const [files, setFiles] = useState([]); const [uploading, setUploading] = useState(false); const [progress, setProgress] = useState(0); const handleFileChange = (e) => { const selectedFiles = Array.from(e.target.files); // Validate files const validFiles = selectedFiles.filter(file => { const maxSize = 5 * 1024 * 1024; // 5MB if (file.size > maxSize) { alert(`${file.name} is too large`); return false; } return true; }); setFiles(validFiles); }; const uploadFiles = async () => { if (files.length === 0) return; setUploading(true); const formData = new FormData(); files.forEach((file, index) => { formData.append(`file${index}`, file); }); try { const response = await fetch('/api/upload', { method: 'POST', body: formData, onUploadProgress: (progressEvent) => { const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); setProgress(percentCompleted); } }); if (response.ok) { alert('Upload successful!'); setFiles([]); } } catch (error) { console.error('Upload failed:', error); } finally { setUploading(false); setProgress(0); } }; return ( <div> <input type="file" multiple onChange={handleFileChange} disabled={uploading} /> {files.length > 0 && ( <div> <h3>Selected Files:</h3> <ul> {files.map((file, index) => ( <li key={index}> {file.name} - {(file.size / 1024).toFixed(2)} KB </li> ))} </ul> </div> )} {uploading && ( <div> <progress value={progress} max="100" /> <span>{progress}%</span> </div> )} <button onClick={uploadFiles} disabled={uploading || files.length === 0}> {uploading ? 'Uploading...' : 'Upload'} </button> </div> ); }

🎯 Drag & Drop Upload

Drag-and-drop functionality user experience ko bahut better banati hai. Users directly files ko drag karke upload kar sakte hain.

Drag and Drop API

HTML5 Drag and Drop API allows users to drag files from their file system and drop them into a designated area on a web page.

Implementation

// HTML <div id="dropZone" class="drop-zone"> <p>Drag & Drop files here or click to select</p> </div> // JavaScript const dropZone = document.getElementById('dropZone'); // Prevent default drag behaviors ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropZone.addEventListener(eventName, preventDefaults, false); document.body.addEventListener(eventName, preventDefaults, false); }); function preventDefaults(e) { e.preventDefault(); e.stopPropagation(); } // Highlight drop zone when item is dragged over it ['dragenter', 'dragover'].forEach(eventName => { dropZone.addEventListener(eventName, highlight, false); }); ['dragleave', 'drop'].forEach(eventName => { dropZone.addEventListener(eventName, unhighlight, false); }); function highlight(e) { dropZone.classList.add('highlight'); } function unhighlight(e) { dropZone.classList.remove('highlight'); } // Handle dropped files dropZone.addEventListener('drop', handleDrop, false); function handleDrop(e) { const dt = e.dataTransfer; const files = dt.files; handleFiles(files); } function handleFiles(files) { [...files].forEach(uploadFile); } function uploadFile(file) { const formData = new FormData(); formData.append('file', file); fetch('/api/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => console.log('Success:', data)) .catch(error => console.error('Error:', error)); }

Interactive Demo: Drag & Drop

🎮 Try Drag & Drop
📁

Drag & Drop Files Here

or click to select files

React Implementation with Preview

import { useState, useCallback } from 'react'; function DragDropUpload() { const [files, setFiles] = useState([]); const [previews, setPreviews] = useState([]); const [isDragging, setIsDragging] = useState(false); const handleDragEnter = useCallback((e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(true); }, []); const handleDragLeave = useCallback((e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(false); }, []); const handleDragOver = useCallback((e) => { e.preventDefault(); e.stopPropagation(); }, []); const handleDrop = useCallback((e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(false); const droppedFiles = Array.from(e.dataTransfer.files); handleFiles(droppedFiles); }, []); const handleFiles = (newFiles) => { setFiles(prev => [...prev, ...newFiles]); // Generate previews for images newFiles.forEach(file => { if (file.type.startsWith('image/')) { const reader = new FileReader(); reader.onloadend = () => { setPreviews(prev => [...prev, { name: file.name, url: reader.result }]); }; reader.readAsDataURL(file); } }); }; const removeFile = (index) => { setFiles(prev => prev.filter((_, i) => i !== index)); setPreviews(prev => prev.filter((_, i) => i !== index)); }; return ( <div> <div className={`drop-zone ${isDragging ? 'dragging' : ''}`} onDragEnter={handleDragEnter} onDragOver={handleDragOver} onDragLeave={handleDragLeave} onDrop={handleDrop} > <p>Drag & Drop files here</p> </div> {previews.length > 0 && ( <div className="preview-grid"> {previews.map((preview, index) => ( <div key={index} className="preview-item"> <img src={preview.url} alt={preview.name} /> <button onClick={() => removeFile(index)}> Remove </button> </div> ))} </div> )} </div> ); }

💡 Best Practices

  • Visual Feedback: Drag karte waqt clear indication do ki drop zone active hai
  • File Preview: Images ke liye thumbnail preview show karein
  • Multiple Files: Multiple files ek saath handle karne ki facility do
  • Error Handling: Invalid files ke liye clear error messages show karein
  • Accessibility: Keyboard navigation aur screen reader support add karein

✅ Client-Side Validation Architecture

Client-side validation user experience improve karta hai aur unnecessary server requests reduce karta hai. Lekin yaad rakhein, server-side validation bhi mandatory hai security ke liye.

Form Validation

Client-side validation is the process of checking user input in the browser before sending it to the server. It provides immediate feedback and reduces server load.

Validation Types

Validation Type Description Example
Required Field must not be empty Name, Email
Format Input must match pattern Email, Phone, URL
Length Min/Max character limit Password (8-20 chars)
Range Numeric value range Age (18-100)
Custom Business logic validation Password strength

Validation Implementation

// Validation Rules const validationRules = { email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Please enter a valid email' }, password: { required: true, minLength: 8, pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/, message: 'Password must contain uppercase, lowercase, number and special character' }, phone: { required: true, pattern: /^\d{10}$/, message: 'Please enter a valid 10-digit phone number' } }; // Validation Function function validateField(fieldName, value) { const rules = validationRules[fieldName]; if (!rules) return { valid: true }; // Required check if (rules.required && !value.trim()) { return { valid: false, message: `${fieldName} is required` }; } // Pattern check if (rules.pattern && !rules.pattern.test(value)) { return { valid: false, message: rules.message }; } // Length check if (rules.minLength && value.length < rules.minLength) { return { valid: false, message: `${fieldName} must be at least ${rules.minLength} characters` }; } return { valid: true }; } // Form Validation function validateForm(formData) { const errors = {}; Object.keys(formData).forEach(field => { const result = validateField(field, formData[field]); if (!result.valid) { errors[field] = result.message; } }); return { valid: Object.keys(errors).length === 0, errors }; }

Interactive Demo: Form Validation

🎮 Try Form Validation

Validation Rules

📧 Valid email format
🔒 Min 8 characters
🔠 One uppercase letter
🔡 One lowercase letter
🔢 One number
✨ One special character
📱 10-digit phone number
✅ Form validated successfully!

React Hook Form Example

import { useForm } from 'react-hook-form'; function RegistrationForm() { const { register, handleSubmit, formState: { errors }, watch } = useForm(); const onSubmit = (data) => { console.log('Form data:', data); // Submit to server }; return ( <form onSubmit={handleSubmit(onSubmit)}> <div> <label>Email</label> <input {...register('email', { required: 'Email is required', pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Invalid email format' } })} /> {errors.email && <span>{errors.email.message}</span>} </div> <div> <label>Password</label> <input type="password" {...register('password', { required: 'Password is required', minLength: { value: 8, message: 'Password must be at least 8 characters' }, pattern: { value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/, message: 'Password must contain uppercase, lowercase, number and special character' } })} /> {errors.password && <span>{errors.password.message}</span>} </div> <button type="submit">Register</button> </form> ); }

⚠️ Important Notes

  • Never Trust Client-Side: Client-side validation bypass ho sakta hai, always server-side validate karein
  • User Feedback: Real-time validation feedback provide karein
  • Accessibility: Error messages screen readers ke liye accessible hone chahiye
  • Performance: Debounce validation for better performance

🚨 Error Handling & Error Boundaries

Error handling ek robust application ka essential part hai. Proper error handling se application crash nahi hota aur user ko clear feedback milta hai.

Error Boundary

Error Boundary is a React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of crashing the entire application.

Error Boundary Implementation

import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false, error: null, errorInfo: null }; } static getDerivedStateFromError(error) { // Update state so next render shows fallback UI return { hasError: true }; } componentDidCatch(error, errorInfo) { // Log error to error reporting service console.error('Error caught by boundary:', error, errorInfo); this.setState({ error: error, errorInfo: errorInfo }); // Send to error tracking service (e.g., Sentry) // logErrorToService(error, errorInfo); } render() { if (this.state.hasError) { // Fallback UI return ( <div className="error-boundary"> <h2>😔 Something went wrong</h2> <p>We're sorry for the inconvenience. Please try refreshing the page.</p> {process.env.NODE_ENV === 'development' && ( <details style={{ whiteSpace: 'pre-wrap' }}> <summary>Error Details</summary> {this.state.error && this.state.error.toString()} <br /> {this.state.errorInfo.componentStack} </details> )} <button onClick={() => window.location.reload()}> Refresh Page </button> </div> ); } return this.props.children; } } // Usage function App() { return ( <ErrorBoundary> <YourApp /> </ErrorBoundary> ); }

Global Error Handler

// Global error handler setup class GlobalErrorHandler { constructor() { this.errors = []; this.setupHandlers(); } setupHandlers() { // Catch unhandled promise rejections window.addEventListener('unhandledrejection', (event) => { console.error('Unhandled promise rejection:', event.reason); this.handleError({ type: 'unhandledRejection', message: event.reason.message || 'Promise rejection', stack: event.reason.stack }); }); // Catch global errors window.addEventListener('error', (event) => { console.error('Global error:', event.error); this.handleError({ type: 'globalError', message: event.message, filename: event.filename, lineno: event.lineno, colno: event.colno, stack: event.error?.stack }); }); } handleError(error) { this.errors.push({ ...error, timestamp: new Date().toISOString() }); // Send to error tracking service this.reportError(error); // Show user-friendly message this.showErrorNotification(error); } reportError(error) { // Send to backend or error tracking service fetch('/api/log-error', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(error) }).catch(err => console.error('Failed to report error:', err)); } showErrorNotification(error) { // Show toast notification or modal const notification = document.createElement('div'); notification.className = 'error-notification'; notification.textContent = 'An error occurred. Our team has been notified.'; document.body.appendChild(notification); setTimeout(() => notification.remove(), 5000); } } // Initialize const errorHandler = new GlobalErrorHandler();

Reusable Error UI Components

// Error Alert Component function ErrorAlert({ error, onClose }) { return ( <div className="error-alert"> <div className="error-icon">⚠️</div> <div className="error-content"> <h4>{error.title || 'Error'}</h4> <p>{error.message}</p> </div> <button onClick={onClose}>✕</button> </div> ); } // Error Page Component function ErrorPage({ error, resetError }) { return ( <div className="error-page"> <h1>Oops! Something went wrong</h1> <p>{error?.message || 'An unexpected error occurred'}</p> <div className="error-actions"> <button onClick={resetError}>Try Again</button> <button onClick={() => window.location.href = '/'}> Go Home </button> </div> </div> ); } // Loading Error Component function LoadingError({ retry }) { return ( <div className="loading-error"> <p>Failed to load data</p> <button onClick={retry}>Retry</button> </div> ); } // Form Error Component function FormError({ errors }) { if (!errors || Object.keys(errors).length === 0) return null; return ( <div className="form-errors"> <h4>Please fix the following errors:</h4> <ul> {Object.entries(errors).map(([field, message]) => ( <li key={field}>{message}</li> ))} </ul> </div> ); }

Error Types & Handling Strategy

Error Type Handling Strategy User Experience
Network Error Retry mechanism, offline mode Show retry button, cache data
Validation Error Inline error messages Highlight fields, show specific errors
Authentication Error Redirect to login, refresh token Clear message, preserve form data
Server Error (5xx) Log error, show fallback UI Generic error message, contact support
Client Error (4xx) Show specific error message Actionable feedback, guide user
Runtime Error Error boundary, log to service Fallback UI, refresh option

Interactive Demo: Error Handling

🎮 Try Error Scenarios

Network Error

Validation Error

Server Error

💡 Error Handling Best Practices

  • User-Friendly Messages: Technical details hide karein, simple language use karein
  • Actionable Feedback: User ko next steps batayein (retry, contact support)
  • Error Logging: Sab errors log karein for debugging
  • Graceful Degradation: Partial functionality provide karein if possible
  • Error Recovery: Automatic retry mechanisms implement karein
  • Context Preservation: User ka data/state preserve karein

🎯 Interview Questions

1. File upload mein FormData ka kya role hai aur isse kaise use karte hain?
Easy ▼

Answer:

FormData ek JavaScript object hai jo form data ko key-value pairs mein encode karta hai, especially file uploads ke liye.

Key Points:

  • Files ko binary format mein send karne ke liye use hota hai
  • Multiple files aur additional data ek saath bhej sakte hain
  • Automatically correct Content-Type header set karta hai
  • XMLHttpRequest ya Fetch API ke saath use hota hai
// Example const formData = new FormData(); formData.append('file', fileInput.files[0]); formData.append('username', 'john'); formData.append('description', 'Profile picture'); fetch('/api/upload', { method: 'POST', body: formData // No need to set Content-Type });
2. Drag and Drop API mein kaunse events important hain aur unka sequence kya hai?
Medium ▼

Answer:

Drag and Drop Events Sequence:

  1. dragstart: Jab user dragging start karta hai
  2. drag: Dragging ke dauran continuously fire hota hai
  3. dragenter: Jab dragged item drop zone mein enter karta hai
  4. dragover: Jab dragged item drop zone ke upar hover karta hai
  5. dragleave: Jab dragged item drop zone se bahar jata hai
  6. drop: Jab item drop hota hai
  7. dragend: Jab drag operation complete hota hai

Important Points:

  • preventDefault() call karna zaroori hai dragover aur drop events mein
  • dataTransfer object se files access karte hain
  • Visual feedback ke liye CSS classes add/remove karein
3. Client-side validation aur server-side validation mein kya difference hai? Dono kyun zaroori hain?
Medium ▼

Answer:

Aspect Client-Side Server-Side
Location Browser mein Server pe
Speed Instant feedback Network delay
Security Bypass ho sakta hai Secure, bypass nahi ho sakta
Purpose UX improvement Data integrity & security

Dono Kyun Zaroori Hain:

  • Client-side: Better UX, instant feedback, reduced server load
  • Server-side: Security, data integrity, business logic enforcement
  • Client-side validation ko JavaScript disable karke bypass kiya ja sakta hai
  • Server-side validation final line of defense hai
4. React mein Error Boundary kya hai aur isse kaise implement karte hain?
Hard ▼

Answer:

Error Boundary ek React component hai jo child component tree mein hone wale JavaScript errors ko catch karta hai aur fallback UI display karta hai.

Implementation:

  • Class component hona chahiye (functional components mein nahi ban sakta)
  • getDerivedStateFromError() - Fallback UI render karne ke liye
  • componentDidCatch() - Error logging ke liye

Kya Catch Nahi Hota:

  • Event handlers mein errors
  • Asynchronous code (setTimeout, promises)
  • Server-side rendering errors
  • Error boundary khud mein errors

Best Practices:

  • Multiple error boundaries use karein different parts ke liye
  • Error logging service integrate karein (Sentry, LogRocket)
  • User-friendly fallback UI provide karein
  • Development mein detailed error info show karein
5. File upload mein progress tracking kaise implement karein?
Medium ▼

Answer:

File upload progress track karne ke liye XMLHttpRequest ka upload.progress event use karte hain.

function uploadWithProgress(file) { const xhr = new XMLHttpRequest(); const formData = new FormData(); formData.append('file', file); // Progress event listener xhr.upload.addEventListener('progress', (e) => { if (e.lengthComputable) { const percentComplete = (e.loaded / e.total) * 100; updateProgressBar(percentComplete); } }); // Load event listener xhr.addEventListener('load', () => { if (xhr.status === 200) { console.log('Upload complete'); } }); // Error event listener xhr.addEventListener('error', () => { console.error('Upload failed'); }); xhr.open('POST', '/api/upload'); xhr.send(formData); } // With Axios axios.post('/api/upload', formData, { onUploadProgress: (progressEvent) => { const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); setProgress(percentCompleted); } });

Key Points:

  • lengthComputable check karna zaroori hai
  • e.loaded aur e.total se percentage calculate karein
  • UI mein progress bar update karein
  • Large files ke liye chunked upload consider karein
6. File upload security considerations kya hain?
Hard ▼

Answer:

File Upload Security Considerations:

  1. File Type Validation:
    • MIME type check karein (client aur server dono pe)
    • File extension validate karein
    • Magic bytes check karein (actual file content)
  2. File Size Limits:
    • Maximum file size enforce karein
    • DoS attacks prevent karne ke liye
  3. File Name Sanitization:
    • Special characters remove karein
    • Path traversal attacks prevent karein (../, etc.)
    • Unique file names generate karein
  4. Storage Security:
    • Files ko web root ke bahar store karein
    • Direct access prevent karein
    • Virus scanning implement karein
  5. Authentication & Authorization:
    • User authentication verify karein
    • Upload permissions check karein
    • Rate limiting implement karein
7. Global error handling strategy kya honi chahiye ek production application mein?
Hard ▼

Answer:

Comprehensive Error Handling Strategy:

  1. Error Boundaries (React):
    • Multiple levels pe error boundaries
    • Component-specific fallback UIs
    • Error recovery mechanisms
  2. Global Error Handlers:
    • window.onerror for global errors
    • unhandledrejection for promise rejections
    • Network error interceptors
  3. Error Logging & Monitoring:
    • Sentry, LogRocket, Bugsnag integration
    • Error context capture (user info, browser, etc.)
    • Source maps for production debugging
  4. User Communication:
    • User-friendly error messages
    • Actionable feedback (retry, contact support)
    • Toast notifications for non-critical errors
  5. Error Recovery:
    • Automatic retry mechanisms
    • Offline mode support
    • State preservation
  6. Performance Monitoring:
    • Error rate tracking
    • Performance metrics
    • User impact analysis