Get progress of an JQuery AJAX request

0

I use this code:

    var formData = new FormData();
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        formData.append('files[]', file, file.name);
    }

    $.ajax({
        url: '/url',
        // dataType: 'json',
        type: 'POST',

        // Form data
        data: formData,

        // Tell jQuery not to process data or worry about content-type
        // You *must* include these options!
        enctype: 'multipart/form-data',
        processData: false,  // tell jQuery not to process the data
        contentType: false, // tell jQuery not to set contentType
        success: function(response){
            if(response != 0){
                alert('file uploaded');
            }
            else{
                alert('file not uploaded');
            }
        },
    });

How can I get file uploading progress?

1 Answer

I found a solution:

var formData = new FormData(); for (var i = 0; i < files.length; i++) { var file = files[i]; formData.append('files[]', file, file.name); }

    $.ajax({
        url: '/url',
        // dataType: 'json',
        type: 'POST',

        // Form data
        data: formData,

        // Tell jQuery not to process data or worry about content-type
        // You *must* include these options!
        enctype: 'multipart/form-data',
        processData: false,  // tell jQuery not to process the data
        contentType: false, // tell jQuery not to set contentType
        beforeSend: function(XMLHttpRequest)
            {
                // Uploading progress
                XMLHttpRequest.upload.addEventListener("progress", function(evt){
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                    }
                }, false);

                // Downloading progress
                XMLHttpRequest.addEventListener("progress", function(evt){
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total
                    }
                }, false);
            },
        success: function(response){
            if(response != 0){
                alert('file uploaded');
            }
            else{
                alert('file not uploaded');
            }
        },
    });
0

Post Answer