Upload Cancellation and Cleanup
What you'll learn: How to gracefully cancel in-flight file uploads and clean up all associated resources and UI elements.
Why Cancellation Matters
When users upload large files, they might change their mind, navigate away, or need to start over. Without proper cancellation, you'll leave hanging network requests consuming bandwidth, orphaned UI elements confusing users, and wasted server resources processing files nobody wants.
Canceling with AbortController
The AbortController is your cancellation mechanism for fetch requests. Create one before starting your upload, pass its signal to fetch(), and call abort() when needed:
let uploadController = new AbortController();
async function uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('/upload', {
method: 'POST',
body: formData,
signal: uploadController.signal // Connect cancellation
});
// Handle success...
} catch (error) {
if (error.name === 'AbortError') {
console.log('Upload cancelled by user');
}
}
}
function cancelUpload() {
uploadController.abort(); // Stops the request immediately
uploadController = new AbortController(); // Create fresh controller
}
Complete Cleanup Checklist
When canceling, you must:
- Abort the network request via
AbortController.abort() - Remove progress indicators from the DOM
- Clear upload queues if handling multiple files
- Revoke object URLs created with
URL.createObjectURL()to free memory - Reset file input values if allowing retry
- Clear any timers or intervals tracking upload progress
- Update application state to reflect cancellation
Think of it like stopping a moving truck: you don't just hit the brakes—you also unload cargo, clear the route for others, and update the delivery manifest.
Key Takeaway: Use AbortController to cancel uploads and systematically clean up all network requests, DOM elements, memory references, and state to prevent resource leaks and UI confusion.