AJAX上傳文件時(shí),有時(shí)比較耗時(shí),需要在界面上顯示下進(jìn)度信息,獲取ajaxSettings中的xhr對(duì)象,為它的upload屬性綁定progress事件的處理函數(shù)
前端代碼
<!DOCTYPE html> <html> <head> <meta charset="utf8"> <title>test upload</title> <!--jquery--> <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script> //頁(yè)面加載完時(shí)加載此函數(shù) window.onload = function() { $('#uploadBtnId').click(function(e) { $('#resultId').html(); //使用FormData對(duì)象來(lái)提交整個(gè)表單,它支持文件的上傳 var formData=new FormData(document.getElementById("myFormId")); formData.append("ddd", 10); //也可使用append追加數(shù)據(jù) $.ajax( { url: 'do_upload.php', data: formData, contentType: false, //false: 自動(dòng)加上正確的Content-Type processData: false, //false: 避開(kāi)jQuery對(duì) formdata 的默認(rèn)處理 enctype: 'multipart/form-data', type: "POST", complete:function(res) { }, success: function (res, status) { $('#resultId').html(res); }, error: function(res){ //錯(cuò)誤處理 }, xhr: function(){ //獲取ajaxSettings中的xhr對(duì)象,為它的upload屬性綁定progress事件的處理函數(shù) var myXhr = $.ajaxSettings.xhr(); if(myXhr.upload){ //檢查upload屬性是否存在 //綁定progress事件的回調(diào)函數(shù) $('#progressId').text(); //清空 myXhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { var percent = "上傳進(jìn)度:" + e.loaded/e.total*100 + "%"; $('#progressId').text(percent); } }, false); } return myXhr; //xhr對(duì)象返回給jQuery使用 }, }); }); } </script> </head> <body> <form id="myFormId" onsubmit="return false"> <!--onsubmit阻止點(diǎn)擊按鈕后瀏覽器自動(dòng)提交表單--> 文件1:<input type="file" name="file1"><br> 文本:<input type="text" name="text1"><br> <button id="uploadBtnId">點(diǎn)擊上傳</button> </form> <p id="progressId"></p> <p id="resultId"></p> </body> </html>
后端代碼
<?php //演示用,僅顯示下上傳上來(lái)的數(shù)據(jù) echo "_FILES<br>"; echo var_dump($_FILES); echo "<br><br>_POST<br>"; echo var_dump($_POST); echo "<br>"; ?>