'How to show the file upload progress in jQuery ajax POST to Google Apps Script WebApp

I have a Google Chrome extension that sends images to Google Drive using jQuery v3.6.0 via AJAX to Google Apps Script WebApp with POST method. This is working correctly. I would like to be able to get the progress of the file upload, I am trying with xhr but when implementing it I get the 405 error in the network console.

This is the code I am using

let reader = new FileReader();
reader.onload = function (e) {
    const values = { data: [...new Int8Array(e.target.result)], filename: "capture.png", mimeType: "image/png" };
    $.ajax({
        // if I delete xhr function works fine
        xhr: function () {
            var xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    $('.percent').text(percentComplete) // show the progress
                }
            }, false)
            return xhr;
        },
        url: "https://script.google.com/macros/s/#####/exec",
        method: "POST",
        dataType: "json",
        data: JSON.stringify(values),
        processData: false,
        contentType: false,
        cache: false,
        success: (data) => {
            console.log(data)
            alert("yes");
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}
reader.readAsArrayBuffer(blob);

Thanks a lot for your help



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source