如何在ajax文件上传中显示进度条

问题描述:

我的代码发布了ajax请求,但没有显示进度条。请帮助更正代码以显示工作进度栏。如何在ajax文件上传中显示进度条

$(document).ready(function() { 
    $("#uploadbutton").click(function() { 
    var filename = $("#file_path$i").val(); //get form data; 

    $.ajax({ 
     type: "html", 
     url: "share.php",//onwhich post ajax data; 
     enctype: 'multipart/form-data', 
     data: { 
     file: filename 
     }, 
     success: function() { 
     alert("Data Uploaded: "); 
     } 
    }); 
}); 
}); 

不幸的是,$.ajax方法不会返回任何progres信息。

而且,也没有跨浏览器解决这个仅使用HTML和JavaScript。我会建议看看Uploadify

这是BlueImp的jQuery的文件上传:

首先,下载:https://github.com/blueimp/jQuery-File-Upload/archives/master

现在,上传JS文件夹。

让您的.html:

<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>jQuery File Upload Example</title> 
    <style> 
    .bar { 
     height: 18px; 
     background: green; 
     } 
    </style> 
    </head> 
    <body> 
    <input id="fileupload" type="file" name="files[]" data-url="server/php/" multiple> 
    <div id="progress"> 
     <div class="bar" style="width: 0%;"></div> 
    </div> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
    <script src="js/vendor/jquery.ui.widget.js"></script> 
    <script src="js/jquery.iframe-transport.js"></script> 
    <script src="js/jquery.fileupload.js"></script> 
    <script> 
    $(function() { 
     $('#fileupload').fileupload({ 
      dataType: 'json', 
      done: function (e, data) { 
       $.each(data.result.files, function (index, file) { 
        $('<p/>').text(file.name).appendTo(document.body); 
       }); 
      } 
     }); 
progressall: function (e, data) { 
     var progress = parseInt(data.loaded/data.total * 100, 10); 
     $('#progress .bar').css(
      'width', 
      progress + '%' 
     ); 
    } 
    }); 
    </script> 
    </body> 
    </html> 

我没有测试过这一点,但它应该是功能。让我知道如果它不是。

可选:在您的.css文件中包含<style></style>的内容。

可选:将.js包含在.js <script src=""></script>标记中。

来源:https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin

@whitneyit:我们可以使用XHR:AJAX的功能来跟踪文件上传这样的事情

$.ajax({ 
       url: 'handler/FileUploader.ashx?FileName=' + file.name, //server script to process data 
       type: 'POST', 
       xhr: function() { 
        myXhr = $.ajaxSettings.xhr(); 
        if (myXhr.upload) { 
         myXhr.upload.addEventListener('progress', progressHandlingFunction, false); 
        } 
        return myXhr; 
       }, 
       success: function (result) {      
        //On success if you want to perform some tasks. 
       }, 
       data: file, 
       cache: false, 
       contentType: false, 
       processData: false 
      }); 
      function progressHandlingFunction(e) { 
       if (e.lengthComputable) { 
        var s = parseInt((e.loaded/e.total) * 100); 
        $("#progress" + currFile).text(s + "%"); 
        $("#progbarWidth" + currFile).width(s + "%"); 
        if (s == 100) { 
         triggerNextFileUpload(); 
        } 
       } 
      }