📁 Upload Files with Fetch, No Page Reload
Traditional form submission reloads page. FormData + Fetch uploads files asynchronously. Progress bar, no page refresh.
📝 Basic Upload
<form id="uploadForm">
<input type="file" name="file" id="fileInput">
<button type="submit">Upload</button>
</form>
<script>
document.getElementById('uploadForm').addEventListener('submit', async (e) => {
e.preventDefault();
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/upload', {
method: 'POST',
body: formData
// Don't set Content-Type header
});
const result = await response.json();
console.log('Uploaded:', result);
});
</script>
🎯 Multiple Files + Progress
// Multiple files
const files = fileInput.files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append('files[]', files[i]);
}
// Progress tracking (XHR not fetch)
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
const percent = (e.loaded / e.total) * 100;
progressBar.value = percent;
}
});
xhr.open('POST', '/upload');
xhr.send(formData);
💡 Tips
- Don’t set Content-Type header (browser sets multipart boundary)
- Use multiple append calls for multiple files
- Validate file size and type before upload
- Show progress bar for large files
“Form submissions reloaded page. Switched to FormData + Fetch. Upload works smoothly, no page refresh. Progress bar shows status. Much better UX.”
