Upload Security and Validation
You'll learn how to validate file uploads on both the client and server to prevent security vulnerabilities and provide better user experience.
Why Validate Twice?
Think of client-side validation as a friendly warning sign and server-side validation as a locked gate. Client-side checks catch honest mistakes instantly (wrong file type, too large), giving users immediate feedback. But malicious users can bypass client-side validation entirely, so server-side validation is your true security layer.
Client-Side Pre-Upload Validation
Before uploading, validate:
function validateBeforeUpload(file) {
const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
const maxSize = 5 * 1024 * 1024; // 5MB
if (!allowedTypes.includes(file.type)) {
alert('Invalid file type. Only JPEG, PNG, and PDF allowed.');
return false;
}
if (file.size > maxSize) {
alert('File too large. Maximum size is 5MB.');
return false;
}
// Sanitize filename to remove dangerous characters
const safeName = file.name.replace(/[^a-zA-Z0-9.-]/g, '_');
return true;
}
Handling Server Validation Errors
When the server rejects a file, handle the response gracefully:
async function uploadWithValidation(file) {
try {
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
if (!response.ok) {
const error = await response.json();
alert(`Upload failed: ${error.message}`);
return;
}
alert('Upload successful!');
} catch (err) {
alert('Network error during upload');
}
}
Never trust client-side validation alone—always verify file type, size, and content on the server. Rename files server-side to prevent path traversal attacks and scan for malware when possible.
Key Takeaway: Client-side validation improves UX by catching errors early, but server-side validation is mandatory for security—always validate file types, sizes, and names on both sides, and handle server rejection errors with clear user feedback.