Question

I have one: http://malsup.com/jquery/form/‎ .. It works okay but I want a upload progress system like facebook, where the window loads while the file is uploading and upload progress is shown at the left bottom corner of the browser. Is there any such jquery ajax form submission that supports file uploading.

Was it helpful?

Solution

you can do that with a XHRListener. i did something similar before some time, here's a snippet of the code i used:

jQuery.ajax({
    url: 'url/to/upload/to',
    data: formMediaData,
    dataType:'json', //return type, in my case it was json
    type: 'post',
    xhr: function(){ 
        // this is the important part
        var xhr = new window.XMLHttpRequest();

        //the event listener will call _very_ often, you might want to check
        // how big the difference between the last percentage and this 
        //percentage is, before you do anything that needs long computing times(!)

        xhr.upload.addEventListener("progress", function(evt){
            //check if the browser can determine the complete size of the data.
            if (evt.lengthComputable) {
                var percentComplete = Math.round((evt.loaded / evt.total)*100);

                //do something with the percentage...

                console.log("upload " +percentComplete + "% done");
            }
        },false);
        return xhr;
    },
    success: function(data){
        //do some tasks after upload
        console.log("upload done");
    }
});

here's how you add files:

html:

<!-- accept="image/*" will only accept file miming to be an image, remember to check if it really is an image... -->
<input type="file" id="uploadBox" accept="image/*" onchange="handleMediaFiles(this.files)" />

js:

var formMediaData= new FormData();

function handleMediaFiles(files){
    for(var i=0;i<files.length;i++){
        formMediaData.append('file_'+i,file[i]);
    }
    fileUpload(); // that's where the ajax is sent  
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top