File upload progress bar with jQuery

2018-12-31 13:56发布

I am trying to implement an AJAX file upload feature in my project. I am using jQuery for this; my code submits the data using AJAX. I also want to implement a file upload progress bar. How can I do this? Is there any way to calculate how much has already been uploaded so that I can calculate the percentage uploaded and create a progress bar?

8条回答
美炸的是我
2楼-- · 2018-12-31 14:36

check this out: http://hayageek.com/docs/jquery-upload-file.php I've found it accidentally on the net.

查看更多
只若初见
3楼-- · 2018-12-31 14:40

I have used the following in my project. you can try too.

ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {

    if (ajax.status) {

        if (ajax.status == 200 && (ajax.readyState == 4)){
            //To do tasks if any, when upload is completed
        }
    }
}
ajax.upload.addEventListener("progress", function (event) {

    var percent = (event.loaded / event.total) * 100;
    //**percent** variable can be used for modifying the length of your progress bar.
    console.log(percent);

});

ajax.open("POST", 'your file upload link', true);
ajax.send(formData);
//ajax.send is for uploading form data.
查看更多
宁负流年不负卿
4楼-- · 2018-12-31 14:43

I've done this with jQuery only:

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();

    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        percentComplete = parseInt(percentComplete * 100);
        console.log(percentComplete);

        if (percentComplete === 100) {

        }

      }
    }, false);

    return xhr;
  },
  url: posturlfile,
  type: "POST",
  data: JSON.stringify(fileuploaddata),
  contentType: "application/json",
  dataType: "json",
  success: function(result) {
    console.log(result);
  }
});
查看更多
何处买醉
5楼-- · 2018-12-31 14:43

If you are using jquery on your project, and do not want to implement the upload mechanism from scratch, you can use https://github.com/blueimp/jQuery-File-Upload.

They have a very nice api with multiple file selection, drag&drop support, progress bar, validation and preview images, cross-domain support, chunked and resumable file uploads. And they have sample scripts for multiple server languages(node, php, python and go).

Demo url: https://blueimp.github.io/jQuery-File-Upload/.

查看更多
唯独是你
6楼-- · 2018-12-31 14:44

This solved my problem

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();

    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        percentComplete = parseInt(percentComplete * 100);
var $link = $('.'+ids);
          var $img = $link.find('i'); 
          $link.html('Uploading..('+percentComplete+'%)');
          $link.append($img);
      }
    }, false);

    return xhr;
  },
  url: posturlfile,
  type: "POST",
  data: JSON.stringify(fileuploaddata),
  contentType: "application/json",
  dataType: "json",
  success: function(result) {
    console.log(result);
  }
});
查看更多
十年一品温如言
7楼-- · 2018-12-31 14:49

here is a more complete looking jquery 1.11.x $.ajax() usage:

<script type="text/javascript">
  function uploadProgressHandler(event)
  {
    $("#loaded_n_total").html("Uploaded "+event.loaded+" bytes of "+event.total);
    var percent = (event.loaded / event.total) * 100;
    var progress = Math.round(percent);
    $("#uploadProgressBar").html(progress + " percent na ang progress");
    $("#uploadProgressBar").css("width", progress + "%");
    $("#status").html(progress +"% uploaded... please wait");
  }

  function loadHandler(event)
  {
    $("#status").html(event.target.responseText);
    $("#uploadProgressBar").css("width", "0%");
  }

  function errorHandler(event){
    $("#status").html("Upload Failed");
  }

  function abortHandler(event){
    $("#status").html("Upload Aborted");
  }

  $("#uploadFile").click(function(event)
                         {
                           event.preventDefault();
                           var file = $("#fileUpload")[0].files[0];
                           var formData = new FormData();
                           formData.append("file1", file);

                           $.ajax({url: 'http://testarea.local/UploadWithProgressBar1/file_upload_parser.php',
                                   method: 'POST',
                                   type: 'POST',
                                   data: formData,
                                   contentType: false,
                                   processData: false,
                                   xhr: function()
                                        {
                                          var xhr = new window.XMLHttpRequest();
                                          xhr.upload.addEventListener("progress",
                                                                      uploadProgressHandler,
                                                                      false
                                                                     );
                                          xhr.addEventListener("load", loadHandler, false);
                                          xhr.addEventListener("error", errorHandler, false);
                                          xhr.addEventListener("abort", abortHandler, false);

                                          return xhr;
                                        }
                                  }
                                 );
                         }
                        );
</script>
查看更多
登录 后发表回答