使用jQuery上传文件上传进度条

时间:2013-03-14 13:11:53

标签: jquery file-upload progress-bar

我正在尝试在我的项目中实现AJAX文件上传功能。我正在使用jQuery;我的代码使用AJAX提交数据。我还想实现一个文件上传进度条。我怎样才能做到这一点?有没有办法计算已上传的内容,以便我可以计算上传的百分比并创建进度条?

8 个答案:

答案 0 :(得分:248)

我只用jQuery完成了这个:

$.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);
  }
});

答案 1 :(得分:125)

注意:此问题与jQuery form plugin有关。如果您正在搜索纯jQuery解决方案,start here。 所有浏览器都没有全面的jQuery解决方案。所以你必须使用插件。我正在使用dropzone.js,它可以轻松备份旧版浏览器。您更喜欢哪个插件取决于您的需求。那里有很多很好的比较帖子。

来自examples

<强> jQuery的:

$(function() {

    var bar = $('.bar');
    var percent = $('.percent');
    var status = $('#status');

    $('form').ajaxForm({
        beforeSend: function() {
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        complete: function(xhr) {
            status.html(xhr.responseText);
        }
    });
}); 

<强> HTML:

<form action="file-echo2.php" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile"><br>
    <input type="submit" value="Upload File to Server">
</form>

<div class="progress">
    <div class="bar"></div >
    <div class="percent">0%</div >
</div>

<div id="status"></div>

你必须用css ...

设置进度条的样式

答案 2 :(得分:17)

我在我的项目中使用了以下内容。 你也可以尝试。

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.

答案 3 :(得分:12)

检查一下:http://hayageek.com/docs/jquery-upload-file.php 我在网上偶然发现了它。

答案 4 :(得分:10)

如果您在项目中使用jquery,并且不想从头开始实施上传机制,则可以使用https://github.com/blueimp/jQuery-File-Upload

他们有一个非常好的api,有多个文件选择,拖放支持,进度条,验证和预览图像,跨域支持,分块和可恢复文件上传。他们有多个服务器语言的示例脚本(node,php,python和go)。

演示网址:https://blueimp.github.io/jQuery-File-Upload/

答案 5 :(得分:5)

这是一个更完整的jquery 1.11.x $ .ajax()用法:

<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>

答案 6 :(得分:5)

这解决了我的问题

$.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 :(得分:4)

Kathir's answer很棒,因为他只用jQuery就解决了这个问题。 我只是想在他的答案中添加一些内容,以便使用漂亮的HTML进度条来处理他的代码:

$.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);

    $('.progress-bar').width(percentComplete+'%');
    $('.progress-bar').html(percentComplete+'%');

  }
}, false);

return xhr;
},
url: posturlfile,
type: "POST",
data: JSON.stringify(fileuploaddata),
contentType: "application/json",
dataType: "json",
success: function(result) {
console.log(result);
}
});

这是进度条的HTML代码,我将Bootstrap 3用于进度条元素:

<div class="progress" style="display:none;">
<div class="progress-bar progress-bar-success progress-bar-striped 
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">
0%
</div>
</div>