带上传的AJAX进度条

时间:2018-04-09 10:19:09

标签: javascript php ajax

我有一个上传表单,它使用AJAX将数据传递给PHP进程文件来处理上传等。我正在尝试在上传文件时向表单添加进度条。

我尝试了一些我通过搜索找到的代码片段,但它们似乎无法正常工作。尝试了以下多种变体:

$.ajax({
xhr: function () {
    var xhr = new window.XMLHttpRequest();
    xhr.upload.addEventListener("progress", function (evt) {
        if (evt.lengthComputable) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                $('.progress').css({
                    width: percentComplete * 100 + '%'
                });
                if (percentComplete === 1) {
                    $('.progress').addClass('hide');
                }
            }
        }
    }, false);

    xhr.addEventListener("progress", function (evt) {
        if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            $('.progress').css({
                width: percentComplete * 100 + '%'
            });
        }
    }, false);

    return xhr;
},
    url: "upload.php",
    type: 'POST',
    data: formData,
    success: function (data) {
        //success
    }
});

他们似乎都没有工作,我已经尝试提醒percentComplete变量,它总是100,任何帮助都将不胜感激,谢谢。

3 个答案:

答案 0 :(得分:5)

我希望这会有所帮助 -

HTML -

<form id="data" method="post" enctype="multipart/form-data">
  <input name="up_vid" type="file" id="up_vid"/>
  <br><br>
  <button id="uploadBtn">Begin Upload</button>
</form>

<br><br>
<div id="status">PROGRESS HERE</div>

JS

$(document).ready(function() {
    $("#uploadBtn").click(function() {
        var formData = new FormData($('#data')[0]);
        console.log(formData);
        $.ajax({
            url: "/echo/html/",
            type: 'POST',
            data: formData,
            xhr: function() {
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener("progress", function(evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        console.log(percentComplete);
                        $('#status').html('<b> Uploading -> ' + (Math.round(percentComplete * 100)) + '% </b>');
                    }
                }, false);
                return xhr;
            },
            success: function(data) {
                $("#status").html('UPLOADED!!');
            },
            cache: false,
            contentType: false,
            processData: false
        });
        return false;
    });
});

现场演示 - https://jsfiddle.net/im4aLL/n7hwfoxd/4/

答案 1 :(得分:0)

解决方案非常简单。我希望只有在执行某些操作时才会触发ajax请求,例如按钮点击或某些事件。

现在,对于该特定事件,您需要启动进度条。有多个库。并且,在收到回复时结束它。

所以,代码会:

$(document).on("click","#button", function(){
  console.log("Start"); //Start progress bar here
  $.ajax({ 
  "type": "POST",
  "url": "upload.php",
  "success": function()
  {
    console.log("end"); //End progress bar here
  }
 });
});

希望,逻辑很容易理解。

答案 2 :(得分:0)

您可以尝试修改此工作模板。

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<style type="text/css">
#progressContainer {
  display: inline-block;
  overflow: hidden;
  width: 400px;
  height: 10px;
  border: 1px solid #333333;
  border-radius: 999px;
}

#progress {
  display: block;
  height: 100%;
  background-color: green;
  border-radius: 999px;
  -o-transition: .1s;
  -ms-transition: .1s;
  -moz-transition: .1s;
  -webkit-transition: .1s;
  transition: .1s;
}
</style>
<div>   
 <form enctype="multipart/form-data" id="form1">
  <input name="file" id="file" type="file" />
  <input type="button" value="Upload" />
 </form>
</div>  
<div id="progress-text1">0%</div>
<span id="progressContainer">
 <span id="progress" style="width:0%;"></span>
</span>
<div id="progress-text2">0%</div>
<div><progress value="0" id="progress1"></progress></div>

<script>
$('#file').on('change', function() {
    $('#progress1').val('0');
});

$(':button').on('click', function() {
    if( $('#file').val() == "" ) {
        alert('Please choose a file before pressing upload..');
        return;
    }
    var FD = new FormData($('#form1')[0]);
    $(FD).serializeArray();

    $.ajax({
        url: 'fileupload-handler.php',
        type: 'POST',
        data: FD,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data){
            alert(data); // Do something with data received
            $('#file').val("");
        },

        // this handles the progress bar
        xhr: function() {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                myXhr.upload.addEventListener('progress', function(e) {
                    var percent_loaded = Math.ceil((e.loaded / e.total)*100);
                    $('#progress-text1').text(percent_loaded+'% has been uploaded..');
                    $('#progress-text2').text(percent_loaded+'% has been uploaded..');
                    $('#progress').css('width', percent_loaded + '%');
                    if (e.lengthComputable) {
                        $('progress').attr({
                            value: e.loaded,
                            max: e.total,
                        });
                    }
                } , false);
            }
            return myXhr;
        }
    });
});
</script>