FormData & File Uploads
Uploading files with FormData, multipart/form-data, progress tracking, and drag-and-drop
Skills taught: api.formdata, api.file-upload, api.multipart, api.upload-progress
File uploads with FormData
// ── Basic file upload with FormData ──
async function uploadFile(file) {
const fd = new FormData();
fd.append('file', file); // the file
fd.append('description', 'My photo'); // extra text fields
fd.append('tags', JSON.stringify(['profile', 'avatar']));
// Do NOT set Content-Type — browser sets multipart/form-data; boundary=...
const res = await fetch('/api/upload', {
method: 'POST',
body: fd,
});
if (!res.ok) throw new Error(`Upload failed: HTTP ${res.status}`);
return res.json(); // { url: 'https://cdn.example.com/photo.jpg', id: '...' }
}
// ── Upload with progress (requires XMLHttpRequest) ──
function uploadWithProgress(file, onProgress) {
return new Promise((resolve, reject) => {
const fd = new FormData();
fd.append('file', file);
const xhr = new XMLHttpRequest();
// Track upload progress
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
const pct = (e.loaded / e.total * 100).toFixed(1);
onProgress(Number(pct), e.loaded, e.total);
}
};
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) resolve(JSON.parse(xhr.responseText));
else reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
};
xhr.onerror = () => reject(new Error('Network error'));
xhr.open('POST', '/api/upload');
xhr.send(fd);
});
}
// ── Drag-and-drop with validation ──
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
const MAX_SIZE_MB = 10;
dropZone.addEventListener('drop', async (e) => {
e.preventDefault();
const files = Array.from(e.dataTransfer.files);
for (const file of files) {
// Validate before upload
if (!ALLOWED_TYPES.includes(file.type)) {
showError(`${file.name}: not a supported image type`);
continue;
}
if (file.size > MAX_SIZE_MB * 1024 * 1024) {
showError(`${file.name}: exceeds ${MAX_SIZE_MB}MB limit`);
continue;
}
// Show preview
const previewUrl = URL.createObjectURL(file);
showPreview(previewUrl, file.name);
// Upload with progress
try {
await uploadWithProgress(file, (pct, loaded, total) => {
updateProgressBar(pct); // Update UI
});
URL.revokeObjectURL(previewUrl); // Clean up
} catch (err) {
showError(`Upload failed: ${err.message}`);
}
}
});
Tip: Never set Content-Type manually for FormData. The boundary string (e.g. `boundary=----WebKitFormBoundary...`) is auto-generated — if you override Content-Type, the server can't parse the file and the upload fails.
Frequently Asked Questions
How do I upload large files without hitting server limits or timeouts?
Use presigned URLs (S3, GCS, Azure Blob). Flow: (1) Frontend asks your backend 'I want to upload a 200MB video'. (2) Your backend calls AWS S3 to generate a presigned URL valid for 15 minutes. (3) Your backend returns the URL to the frontend. (4) Frontend uses fetch() or XMLHttpRequest to PUT the file directly to S3 — no traffic goes through your server. Benefits: no server timeout, no 100MB body limit, bandwidth goes directly to S3. S3 also supports multipart uploads (split into 5MB+ chunks, upload in parallel, reassemble).