How to get progress from XMLHttpRequest

Cover Image for How to get progress from XMLHttpRequest
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

How to Get Progress from XMLHttpRequest 📶

Introduction 🔍

Do you ever wonder how to display a progress bar when uploading large files using XMLHttpRequest? 📁 It seems like a basic and essential feature to have, as the client knows the number of bytes uploaded or downloaded. 🔄 But unfortunately, the standard XMLHttpRequest API does not directly support this. 😞 However, worry not! In this blog post, we will explore a few simple solutions to tackle this common problem. Let's dive in! 🏊‍♂️

The Problem and Challenges 🤔

The primary issue with the standard XMLHttpRequest is the lack of built-in progress information. 😓 To address this, the default workaround is to continuously poll the server for progress updates. 👀 While this method works, it comes with its own set of challenges. Let's take a look at them:

  1. Complicated server-side code: Constantly polling the server requires additional code on the server-side to handle and respond to these requests. This can significantly increase the complexity of your codebase. 🧩

  2. Poor upstream connections: Uploading large files can be a painstakingly slow process, especially when most ISPs offer poor upstream bandwidth. When the user's connection is struggling, making extra requests for progress updates adds further burden to the responsiveness. ⏳

Solutions at Hand 🙌

Although the standard API lacks the progress functionality, there are alternative approaches to overcome this limitation. Let's explore a couple of solutions:

1. Use the non-standard progress event 🔄

Some modern browsers provide a non-standard extension to XMLHttpRequest called the progress event. 🌐 This event allows you to track the progress of an ongoing request. Here's a simple example of how you can utilize it:

const xhr = new XMLHttpRequest();

xhr.addEventListener('progress', (event) => {
  if (event.lengthComputable) {
    const percent = (event.loaded / event.total) * 100;
    console.log(`Progress: ${percent.toFixed(2)}%`);
  }
});

xhr.open('POST', 'your-upload-endpoint');
xhr.send(formData);

By listening to the progress event, you can access the loaded and total attributes in the event object, which represent the number of bytes uploaded or downloaded and the total file size, respectively. 📤

However, keep in mind that this approach should be used sparingly as it is non-standard and may not be supported across all browsers. 🚨

2. Utilize newer technologies such as Fetch API 🌟

Another solution is to move away from XMLHttpRequest and embrace newer technologies like the Fetch API. 🚀 The Fetch API provides a more modern and streamlined way to make HTTP requests, including support for tracking progress.

Here's an example of using the Fetch API with progress tracking:

fetch('your-upload-endpoint', {
  method: 'POST',
  body: formData,
}).then((response) => {
  const reader = response.body.getReader();
  let totalBytes = 0;
  let loadedBytes = 0;

  return reader.read().then(function processResult(result) {
    if (result.done) {
      console.log('Upload complete!');
      return;
    }

    loadedBytes += result.value.length;
    totalBytes = response.headers.get('Content-Length');

    const percent = (loadedBytes / totalBytes) * 100;
    console.log(`Progress: ${percent.toFixed(2)}%`);

    return reader.read().then(processResult);
  });
});

In this example, we use the Fetch API's streaming feature to access a ReadableStream from the response body. This allows us to track progress by reading chunks of data and calculating the percentage based on the total bytes. 📊

The Fetch API offers more control and flexibility, making it an excellent alternative for handling progress tracking.

Conclusion and Next Steps 🏁

While the standard XMLHttpRequest lacks native progress tracking, there are viable alternatives to overcome this limitation. 🚀 By utilizing non-standard features like the progress event or embracing modern technologies such as the Fetch API, you can display progress bars and provide a more interactive user experience during file uploads. 📥

Now that you have learned how to get progress from XMLHttpRequest, it's time to take action and implement these solutions in your own projects. 💪 Remember, user engagement can be significantly enhanced by utilizing progress bars and providing real-time feedback on long-running processes. So go ahead, experiment, and transform your user experiences like a pro! 🌟


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello