Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8332605
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T02:46:15+00:00 2026-06-09T02:46:15+00:00

Hi guys! I’ve got a little problem with my HTML5 XMLHttprequest uploader. I read

  • 0

Hi guys!

I’ve got a little problem with my HTML5 XMLHttprequest uploader.

I read files with Filereader class from multiple file input, and after that upload one at the time as binary string. On the server I catch the bits on the input stream, put it in tmp file, etc. This part is good. The program terminated normally, send the response, and I see that in the header (eg with FireBug).
But with the JS, I catch only the last in the ‘onreadystatechange‘.

I don’t see all response. Why? If somebody can solve this problem, it will be nice 🙂

You will see same jQuery and Template, don’t worry 😀

This is the JS:

function handleFileSelect(evt)
{
    var files = evt.target.files; // FileList object

    var todo = {
            progress:function(p){
                $("div#up_curr_state").width(p+"%");
                },

            success:function(r,i){

                $("#img"+i).attr("src",r);
                $("div#upload_state").remove();
                },

            error:function(e){
                alert("error:\n"+e);
                }
        };


    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {
        // Only process image files.
        if (!f.type.match('image.*')) {
            continue;
        }

        var reader = new FileReader();
        var row = $('ul#image_list li').length;
            row = row+i;
        // Closure to capture the file information.
        reader.onload = (function(theFile,s) {
            return function(e) {
            // Render thumbnail.
            $("span#prod_img_nopic").hide();
            $("div#prod_imgs").show();
            var li = document.createElement('li');
            li.className = "order_"+s+" active";
            li.innerHTML = ['<img class="thumb" id="img'+s+'" src="', e.target.result,
                                '" title="', escape(theFile.name), '"/><div id="upload_state"><div id="up_curr_state"></div>Status</div>'].join('');
            document.getElementById('image_list').insertBefore(li, null);
            };
        })(f,row);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);

        //upload the data
        //@param object fileInputId     input file id
        //@param int    fileIndex       index of fileInputId
        //@param string URL             url for xhr event
        //@param object todo            functions of progress, success xhr, error xhr
        //@param string method          method of xhr event-def: 'POST'

        var url = '{/literal}{$Conf.req_admin}{$SERVER_NAME}/{$ROOT_FILE}?mode={$_GET.mode}&action={$_GET.action}&addnew=product&imageupload={literal}'+f.type;

        upload(f, row, url, todo);
}

the upload function:

function upload(file, fileIndex, Url, todo, method)
 {
        if (!method) {
            var method = 'POST';
        }

        // take the file from the input

        var reader = new FileReader();
        reader.readAsBinaryString(file); // alternatively you can use readAsDataURL
        reader.onloadend  = function(evt)
        {
                // create XHR instance
                xhr = new XMLHttpRequest();

                // send the file through POST
                xhr.open(method, Url, true);

                // make sure we have the sendAsBinary method on all browsers
                XMLHttpRequest.prototype.mySendAsBinary = function(text){
                    var data = new ArrayBuffer(text.length);
                    var ui8a = new Uint8Array(data, 0);
                    for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);
                    var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)(); 
                    bb.append(data);
                    var blob = bb.getBlob();
                    this.send(blob);
                }

                // let's track upload progress
                var eventSource = xhr.upload || xhr;
                eventSource.addEventListener("progress", function(e) {
                    // get percentage of how much of the current file has been sent
                    var position = e.position || e.loaded;
                    var total = e.totalSize || e.total;
                    var percentage = Math.round((position/total)*100);
                    // here you should write your own code how you wish to proces this
                    todo.progress(percentage);        
                });

                // state change observer - we need to know when and if the file was successfully uploaded
                xhr.onreadystatechange = function()
                {  
                        if(xhr.status == 200 && xhr.readyState == 4)
                        {                                
                            // process success                               
                            resp=xhr.responseText;

                            todo.success(resp,fileIndex);
                        }else{
                            // process error
                            todo.error(resp);
                        }                            
                };

                // start sending
                xhr.mySendAsBinary(evt.target.result);
        };
   }

    }
}

and the starter event

document.getElementById('files').addEventListener('change', handleFileSelect, false);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T02:46:16+00:00Added an answer on June 9, 2026 at 2:46 am

    It’s a quite small mistake: You forgot to add a var statement:

        // create XHR instance
        var xhr = new XMLHttpRequest();
    //  ^^^ add this
    

    With a readystatechange handler function like yours

    function() {  
        if (xhr.status == 200 && xhr.readyState == 4) {       
            resp=xhr.responseText; // also a missing variable declaration, btw
            todo.success(resp,fileIndex);
        } else {
            todo.error(resp);
        }                            
    }
    

    only the latest xhr instance had been checked for their status and readyState when any request fired an event. Therefore, only when the last xhr triggers the event itself the success function would be executed.

    Solution: Fix all your variable declarations, I guess this is not the only one (although affecting the behaviour heavily). You also might use this instead of xhr as a reference to the current XMLHttpRequest instance in the event handler.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

guys i got a php file that use it as xml for a flash
guys, I have the problem when copying database from local assets folder to /data/data/package_name/databases
guys. I have a strange problem. I try to write unit-tests to web-app. I
Guys, I've came across this problem I can't resolve myselg, I'm pretty sure I
Guys, what is function called after my class loaded, where i can call self
Guys i am facing a problem with wildcard character in jquery. Please help if
Guys that is code copied from a book (Programming Windows 5th edition): #include <windows.h>
Guys if I have class like below: template<class T> class X { T** myData_;
Guys, I am using dynamic programming approach to solve a problem. Here is a
guys i have a xml file which is like this: <Point TestFlag=0 id=1 name=Conversation

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.