What are some reasons why the XMLHttpRequest ProgressEvent.lengthComputable property could return a value of

I've been struggling to implement an upload progress bar using the XMLHttpRequest level 2 support for progress events in HTML5.

Most examples I come across show adding an event listener to the progress event like this:

req.addEventListener("progress", function(event) {
    if (event.lengthComputable) {
        var percentComplete = Math.round(event.loaded * 100 / event.total);
        console.log(percentComplete);
    }
}, false);

However, I keep encountering the issue where event.lengthComputable is always false. This problem persists in browsers like Safari 5.1.7 and Firefox 12 on OSX.

My website is Django-based, and I face the same challenge on both my development and production environments.

Below is the complete code snippet I'm using for form uploads with jQuery:

form.submit(function() {
    // Gather the data.
    var data = form.serializeArray();
    data.splice(0, 0, {
        name: "file",
        value: form.find("#id_file").get(0).files[0]
    });
    // Build the form data.
    var fd = new FormData();
    $.each(data, function(_, item) {
        fd.append(item.name, item.value);
    });
    // Send the request.
    var req = new XMLHttpRequest();
    req.addEventListener("progress", function(event) {
        if (event.lengthComputable) {
            var percentComplete = Math.round(event.loaded * 100 / event.total);
            console.log(percentComplete);
        }
    }, false);
    req.addEventListener("load", function(event) {
        if (req.status == 200) {
            var responseData = $.parseJSON(event.target.responseText);
            if (responseData.success) {
                console.log("Success!")
            } else {
                console.log("Failed!")
            }
        } else {
            console.log("Something went wrong!")
        }
    }, false);
    req.addEventListener("error", function() {
        console.log("An error occurred!")
    }, false);
    req.open("POST", "/my-bar/media/add/");
    req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    req.send(fd);
    // Prevent default submission.
    return false;
});

I've spent hours troubleshooting this issue. Any assistance would be greatly appreciated!

Answer №1

After some research, I stumbled upon this solution provided by @TechExpert:

I admit, I made a similar error.

This was the line I mistakenly wrote:

xhr.onprogress = uploadProgress;

The correct implementation should actually be:

xhr.upload.onprogress = uploadProgress;

Answer №3

Dealing with the challenge of sending multiple large files via AJAX (xmlhttprequest) was a real struggle for me.

After much trial and error, I finally found a solution that worked well. Here is the complete script that now successfully handles this task:

<input type="file" multiple name="file" id="upload_file" onchange="handleFiles(this)">

In addition to adding the above line into your HTML page, make sure to include the following script as well:

<script type="text/javacript">
    var filesArray;
    function sendFile(file)
    {
        var uri = "<URL TO PHP FILE>";
        var xhr = new XMLHttpRequest();
        var fd = new FormData();

        var self = this;

        xhr.upload.onprogress = updateProgress;
        xhr.addEventListener("load", transferComplete, false);
        xhr.addEventListener("error", transferFailed, false);
        xhr.addEventListener("abort", transferCanceled, false);
        xhr.open("POST", uri, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                alert(xhr.responseText); // handle response.
            }
        };
        fd.append('myFile', file);
        // Initiate a multipart/form-data upload
        xhr.send(fd);
    }
    function updateProgress (oEvent)
    {
        if (oEvent.lengthComputable)
        {
            var percentComplete = oEvent.loaded / oEvent.total;
            console.log(Math.round(percentComplete*100) + "%");
        } else {
            // Unable to compute progress information since the total size is unknown
            console.log("Total size is unknown...");
        }
    }

    function transferComplete(evt)
    {
        alert("The transfer is complete.");
    }

    function transferFailed(evt)
    {
        alert("An error occurred while transferring the file.");
    }

    function transferCanceled(evt)
    {
        alert("The transfer has been canceled by the user.");
    }
    function handleFiles(element)
    {
        filesArray = element.files;
        if (filesArray.length > 0)
        {
            for (var i=0; i<filesArray.length; i++)
            {
                sendFile(filesArray[i]);
            }
            filesArray = '';
        }
    }
    </script>

You can view the result in the console log.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is Angular's approach to handling a dynamic and unprocessed JSON object?

When a JSON file is placed under assets, accessing it using something like http://localhost:4200/myapp.com/assets/hello.json will fetch the JSON file directly without any graphical user interface. This indicates that Angular must be able to return a raw JS ...

Having trouble with ng-click not correctly updating values within ng-repeat

Here is the code snippet: <div ng-repeat="data in products"> <div class=edit ng-click="dataUI.showEdit = true; content = data;"> </div> <div ng-repeat="renew in data.renewed"> <div class=edit ng-click="dataUI ...

Investigate issues with POST data requests

I recently utilized a REST API to send a POST request. Upon clicking on the function addmode(), a textbox is displayed allowing users to input data. However, upon clicking the save() button, an unexpected error occurs and redirects to a PUT Request. Using ...

attempting to communicate with Postman but encountering an error in the process

Upon attempting to send a request through Postman, I encountered an error. Nodemon is operational and the server is active in the terminal. index.server.js file //jshint esversion:6 const express = require("express"); const env = require("d ...

- The click function is failing to work after an ajax call [Potential event delegation problem]

I have a webpage where I update the contents of an unordered list using $.get() every 5 seconds. The issue I am facing is that the click function for the list items is not working properly. Even though the list items are being updated correctly, there se ...

Error: The property 'target' cannot be read

I'm seeking to enhance a value by pinpointing a specific element within a loop. <div *ngFor="let item of items; let i = index"> <ion-button (click)="increment(i)"> <ion-icon name="add"></ion ...

The interplay between javascript and PL/SQL tasks in a dynamic scenario

I'm attempting to run multiple pl/sql blocks within a Dynamic Action, providing real-time feedback to the user through a modal dialog displaying the current status. Here is an example of what I am trying to achieve: Processing Step 1... /*Run pl/s ...

Center-aligned footer with a sleek right border in Bootstrap 4.1.1

Presenting my design concept for the footer: https://i.sstatic.net/kxdXJ.png Here is the code snippet for the footer design utilizing Bootstrap 4.1.1: .mainfooter-area { background: #404044; padding: 100px 0; } ... <link href="https://cdnjs.cl ...

The way in which the DOM responds to adding or deleting elements from its structure

My typical method for displaying a popup involves adding an empty div tag and a button to the webpage: <div id="popupDiv"></div> <input type="button" id="popupButton" /> I then use jQuery to handle a button click event, make an ajax cal ...

Create a JavaScript button that redirects to a different page within a React application

I am creating a div element using a for-loop and I want to link each div to the "/campaign" page with its respective id. When a div is clicked, I want it to navigate to the "/campaign/id" page and pass the id to the Campaign component. class Home extends ...

How to Implement Multiple OR Statements in SharePoint 2010 Using Jquery and JSON Rest

Struggling to create a multiple OR variable, but it just won't work. Is there an issue with my syntax or logic? var category = (i.Category == "Electric" ? "E" : i.Category == "Power Module" ? "PM" : i.Category == "Branch Office" ? "BO" : ""); After ...

The rendered attribute of h:outputLabel is not functioning correctly when triggered by a click event from an a4j:commandButton

Can someone assist me in resolving this problem with JSF? When the bean.displayInd is changed from false to true, the outputLabel is not rendering. When the commandButton is clicked, the filterRequest method is triggered which sets displayInd to true. H ...

Transforming screen recording video chunks from blob into multipart for transmission via Api as a multipart

Seeking guidance in Angular 8 - looking for advice on converting screen recorded video chunks or blogs into a multipart format to send files via API (API only accepts multipart). Thank you in advance! ...

Attempting to display a singular form

Currently, I am working on a MERN app and encountering a small issue... I am developing an application where users can create rooms and within those rooms, they can plan their daily activities. It's similar to a TODO app but more intricate. I wanted ...

How to perfectly position an image within a fixed full screen container

When you click on a thumbnail image, a full-screen overlay with a larger version of the image will be triggered using JavaScript. To ensure that the image is centered and resized inside the black overlay when the browser window size changes, I attempted t ...

assisting with the transition effect using CSS3, JS, or jQuery

I am looking to alter the background-image of this particular image when transitioning to another one from my images folder, similar to this example. Below is the code that I have: CSS .image { position: relative; overflow: hidden; -webkit-tr ...

One way to retrieve API responses in node js is by utilizing callback functions

I am currently exploring callback functions and utilizing the request module in node js to retrieve information. As Javascript is asynchronous, I am struggling with how to properly return my response. Below are snippets of my code. In my app.js file: var ...

React: the function is returning as undefined

Description I am encountering an issue with a function in a functional component, as it keeps returning undefined. Despite having all the necessary data defined and accurate within the function including tableData and subtractedStats. This seems to be a ...

Include a new feature within an onClick event

I'm looking to implement a single page application using React.js and I want to incorporate a list within a material-ui drawer. The goal is to dynamically add elements to an array every time a button is clicked, but I'm stuck on how to write this ...

Is it possible to configure the async.retry method to retry even upon successful queries, depending on a specific condition?

Currently, I am delving into the node.js async module and wondering if it's possible to modify the behavior of the async.retry method. Specifically, I'd like it to retry even on successful operations but halt based on a certain condition or respo ...