'Picture upload interrupted in JavaScript

Consider the following script:

    function uploadPicture(myindex, stringid)
{
    uploadingpicture = true;
    let fileform = document.getElementById("fileform" + myindex);
    let file = fileform.elements.namedItem('file').files[0];
    let type = file.type;
    let size = file.size;
    console.log('User is trying to upload a ' + type + ' file called ' + stringid + ' (size: ' + size + ')');

    let contents = new FileReader(); // no arguments
    contents.readAsDataURL(file);

    contents.onloadend = function ()
    {

        let filename;
        let client;
        let filecontainer = document.getElementById('file' + myindex);
        if (filecontainer != null)
        {
            filename = filecontainer.innerHTML.replace(/\+/g, '+').replace(/&/g, '&').replace(/#/g, '#').replace(/%/g, '%');
        }
        let clientcontainer = document.getElementById('myclient');
        if (clientcontainer != null)
        {
            client = clientcontainer.innerHTML.replace(/\+/g, '+').replace(/&/g, '&').replace(/#/g, '#').replace(/%/g, '%');
        }

        postRequest(
            'ajaxcalls/ajaxUploadPicture.php', // url
            '&client=' + client +
            '&stringid=' + stringid +
            '&filename=' + filename +
            '&field=' + myindex +
            '&type=' + type +
            '&contents=' + contents.result,
            function (responseText)
            {
                return drawOutputUploadPicture(myindex, responseText);
            },  // success
            drawErrorUploadPicture   // error
        );
    }

    contents.onerror = function ()
    {
        console.log(contents.error);
    };

}

function drawOutputUploadPicture(myindex, responseText)
{
    console.log('RESPONSE: ' + responseText);
    let feedbackElement = document.getElementById('feedback' + myindex);
    if (feedbackElement !== null)
    {
        feedbackElement.innerHTML = responseText;
    }
    uploadingpicture = false;
}

function drawErrorUploadPicture()
{
    uploadingpicture = false;
}

This script works. However, the upload is almost always interrupted halfway, so the result is a partial picture: sometimes you see half, sometimes a quarter, but almost never the whole picture. There are no errors. There is no upload limit.

What could be causing this?



Solution 1:[1]

I found out the cause of this.

The form calling this JavaScript used a Submit button with type="submit", so that the form being submitted interrupted the actual upload. I was able to solve this by changing the type into type="button".

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Loek van Kooten