Jquery and ajax progress bar reaching 100% too fast

岁酱吖の 提交于 2020-05-13 07:46:05

问题


I have a working progress bar which uploads files to an S3 bucket in AWS. There are no issues with the process or whatsoever but what is a bit off is that the progress bar is a bit too fast. Basically, I upload a file, progress bar fills up in about 5 seconds and then I need to wait for another 5 seconds for the file to actually appear in the bucket(the page refreshes once the upload completes). With larges files I wait for 5 minutes or more for them to upload but I see the progress bar at 100% after just a few seconds. Here's the code:

<form class="uploadForm" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="button" class="btn btn-info" id="upload" value="Choose a file">
    <input type="file" id="uploadFile">
    <input type="submit" class="btn btn-primary" id="uploadButton" value="Upload">
</form>
<div class="progress">
    <div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
</div>

Here's my ajax/jquery code:

$.ajax({
  xhr: function(){
    var xhr = new window.XMLHttpRequest();
    xhr.upload.addEventListener('progress', function(e){
        if(e.lengthComputable) {
          var percent = Math.round((e.loaded / e.total) * 100);
          $('#progressBar').attr('aria-valuenow', percent).css('width', percent + "%").text(percent + "%");
        }
    });
    return xhr;
  },
  url: "{% url 'project:uploadFile' %}",
  type: 'post',
  data: fileData,
  cache: false,
  processData: false,
  contentType: false,
  success: function(data){
    location.reload();
  }
});

So after the file has uploaded the page refreshes and the file is there but the progress bar doesn't really reflect the real upload progress. What am I doing wrong?

来源:https://stackoverflow.com/questions/48137163/jquery-and-ajax-progress-bar-reaching-100-too-fast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!