简体   繁体   中英

Ajax File-upload progress without any plugin Jquery

How to get progress of File upload in JQuery such that I can update status bar about file upload.

Below is my file upload code using Ajax in JQuery:

         $('button').click(function(e) {
             var formData = new FormData($('#myform')[0]);
               $.ajax({
                  url: 'FileUploadExample',
                  type: 'post',
                  data: formData,
                  async: true,
                  cache: true,
                  contentType: false,
                  processData: false,
                  success: function(returndata) {
                  }
             });

       });

While googling this issue I cam across jquery.form.min.js plugin which have option uploadProgress .

How can I get progress of upload without using any plugin in JQuery/JavaScript.

Using JQuery xhr element, like this

var formData = new FormData($('#myForm')[0]);
$.ajax({
    url: url,
    type: 'POST',
    xhr: function() {
        myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){
            myXhr.upload.addEventListener('progress',progressHandlerFunction, false);
        }
        return myXhr;
    },
    data: formData,
    cache: false,
    contentType: false,
    processData: false
});

and in progressHandlerFunction you can access e.loaded and e.total of progress like

progressHandlerFunction(e)
{
    console.log(e.total+""+e.loaded);
}

$.ajaxSettings.xhr(); is the real XMLHttpRequest element, and in native JS you can bind a handler on XMLHttpRequest.upload onProgress event, then you can get the event.total and event.loaded, The progress event will trigger every time event.loaded changes value.

  • event.total = Total size of HTTP request.
  • event.loaded= Currently uploaded value.

You can do anything with this 2, you can get the percentage by doing var percent=Math.round((event.loaded/event.total) * 100); and adjust your loading bar width accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM