Get Byte Position during Upload Loop : <p>I am working on a function that will write data to a remote server in chunks using a 3rd party API. Through some help on Stack Overflow I was able to accomplish this, where it is now working as expected. The problem is that I can only get a single 16kb chunk to write as I will need to advance the <code>pos</code> of where the next bytes are written to.</p>

<p>The initial write starts at 0 easily enough. Due to my unfamiliarity with this though, I am unsure if the next <code>pos</code> should just be 16 or what. If it helps, the API call <code>writeFileChunk()</code> takes 3 parameters, filepath (str), pos (int64), and data (base64 encoded string).</p>

<pre><code>    reader.onload = function(evt)
    {
        // Get SERVER_ID from URL
        var server_id = getUrlParameter('id');

        $("#upload_status").text('Uploading File...');
        $("#upload_progress").progressbar('value', 0);

        var chunkSize = 16&lt;&lt;10;
        var buffer = evt.target.result;
        var fileSize = buffer.byteLength;
        var segments = Math.ceil(fileSize / chunkSize); // How many segments do we need to divide into for upload
        var count = 0;

        // start the file upload
        (function upload()
        {
            var segSize = Math.min(chunkSize, fileSize - count * chunkSize);

            if (segSize &gt; 0)
            {
                $("#upload_progress").progressbar('value', (count / segments));

                var chunk = new Uint8Array(buffer, count++ * chunkSize, segSize); // get a chunk
                var chunkEncoded = btoa(String.fromCharCode.apply(null, chunk));

                // Send Chunk data to server
                $.ajax({
                    type: "POST",
                    url: "filemanagerHandler.php",
                    data: { 'action': 'writeFileChunk', 'server_id': server_id, 'filepath': filepath, 'pos': 0, 'chunk': chunkEncoded },
                    dataType: 'json',
                    success: function(data)
                    {
                        console.log(data);
                        setTimeout(upload, 100);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown)
                    {
                        alert("Status: " + textStatus); alert("Error: " + errorThrown); alert("Message: " + XMLHttpRequest.responseText);
                    }
                });
            }
            else
            {
                $("#upload_status").text('Finished!');
                $("#upload_progress").progressbar('value', 100);

                getDirectoryListing(curDirectory);
            }
        })()
    };
</code></pre>
