Course contentsShow
← Web Development
Lesson 2669 of 2,98248. File Uploads and HandlingFree lesson

File Type Validation

Checking file MIME types and extensions in JavaScript to validate uploads before sending to the server.

File Type Validation

What you'll learn: How to verify file types client-side before upload to prevent invalid files from reaching your server.

Why Validate Files in JavaScript?

Before users upload files to your server, you want to catch problems early. Imagine a "photos only" uploader that receives Word documents—server bandwidth wasted, user frustrated. Client-side validation acts as your first line of defense (though never your only defense—always validate server-side too).

Two Validation Strategies

Check the File Extension

The simplest approach: examine the filename ending.

const fileInput = document.querySelector('input[type="file"]');

fileInput.addEventListener('change', (e) => {
  const file = e.target.files[0];
  const allowedExtensions = ['.jpg', '.png', '.gif'];
  const fileName = file.name.toLowerCase();
  
  const isValid = allowedExtensions.some(ext => fileName.endsWith(ext));
  
  if (!isValid) {
    alert('Please upload only JPG, PNG, or GIF images');
    fileInput.value = ''; // Clear the invalid selection
  }
});

The problem: Users can rename virus.exe to virus.jpg. Extensions are easily spoofed.

Check the MIME Type

More reliable: inspect the file's actual MIME type (the browser reads this from file headers).

fileInput.addEventListener('change', (e) => {
  const file = e.target.files[0];
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  
  if (!allowedTypes.includes(file.type)) {
    alert(`Invalid file type: ${file.type}`);
    fileInput.value = '';
  }
});

The file.type property provides the MIME type string (e.g., "image/jpeg", "application/pdf").

Best Practice: Combine Both

Check extension and MIME type for stronger validation—like checking both someone's ID and their face.

Key Takeaway: Use file.type to validate MIME types and file.name to check extensions in JavaScript before upload, but remember client-side validation is only UX—always validate server-side for security.