乐闻世界logo
搜索文章和话题

How to get progress from XMLHttpRequest

1个答案

1

When performing file uploads or downloads, understanding the current progress is crucial for enhancing user experience. When using XMLHttpRequest (XHR) for these operations, you can monitor progress by listening for progress events.

Steps:

  1. Create an XMLHttpRequest object: First, instantiate an XMLHttpRequest object.

    javascript
    var xhr = new XMLHttpRequest();
  2. Register event listeners: For download progress, listen for the progress event. For upload progress, listen for the upload.onprogress event. These events trigger multiple times during data transfer, providing progress information.

    javascript
    // Listen for download progress xhr.onprogress = function(event) { if (event.lengthComputable) { var percentComplete = event.loaded / event.total * 100; console.log('Download progress: ' + percentComplete.toFixed(2) + '%'); } }; // Listen for upload progress xhr.upload.onprogress = function(event) { if (event.lengthComputable) { var percentComplete = event.loaded / event.total * 100; console.log('Upload progress: ' + percentComplete.toFixed(2) + '%'); } };
  3. Set up the request and send: Configure the request parameters appropriately, including the URL and request method, then send the request.

    javascript
    xhr.open('GET', 'path/to/resource'); xhr.send();

Practical Application Example:

Suppose you are developing a web application where users need to upload video files, and you want to display a progress bar during the upload process.

javascript
function uploadFile(file) { var xhr = new XMLHttpRequest(); // Set up the request method and URL for uploading xhr.open('POST', '/upload/video'); // Set up the progress bar logic xhr.upload.onprogress = function(event) { if (event.lengthComputable) { var percentComplete = event.loaded / event.total * 100; // Assuming there is a progress bar element document.getElementById('uploadProgress').style.width = percentComplete.toFixed(2) + '%'; } }; // Set up logic for request completion xhr.onload = function() { if (xhr.status === 200) { console.log('Upload successful'); } else { console.log('Upload failed: ' + xhr.statusText); } }; // Send the request var formData = new FormData(); formData.append('file', file); xhr.send(formData); }

In this example, we create an uploadFile function to handle file uploads. We listen for the upload.onprogress event to update the progress bar on the page, and handle success or failure logic using xhr.onload after the upload completes.

Summary:

By listening for the progress and upload.onprogress events of XMLHttpRequest, you can effectively track the upload and download progress of files. This not only improves user experience but also simplifies problem diagnosis and handling.

2024年7月26日 21:41 回复

你的答案