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

Upload Cancellation and Cleanup

Properly cancel ongoing uploads with AbortController and clean up temporary resources and UI state.

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:

  1. Abort the network request via AbortController.abort()
  2. Remove progress indicators from the DOM
  3. Clear upload queues if handling multiple files
  4. Revoke object URLs created with URL.createObjectURL() to free memory
  5. Reset file input values if allowing retry
  6. Clear any timers or intervals tracking upload progress
  7. 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.