<div style="padding: 10px;"> <div class="progress-bar" style="display: none;"> <div class="progress-bar-plan"></div> <div class="progress-bar-font"> 0% </div> </div> </div>
$("#btn_save").click(function () { var formData = new FormData(); if ($("input[type='file']").length > 1) { $(".progress-bar").show(); $(".progress-bar-plan").css("background-color", "red"); $("input[type='file']").each(function (index, item) { formData.append("file", $("input[type='file']")[index].files[0]); }) }
//首先封装一个方法 传入一个监听函数 返回一个绑定了监听函数的XMLHttpRequest对象 var xhrOnProgress = function (fun) { xhrOnProgress.onprogress = fun; //绑定监听 //使用闭包实现监听绑 return function () { //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象 var xhr = $.ajaxSettings.xhr(); //判断监听函数是否为函数 if (typeof xhrOnProgress.onprogress !== 'function') return xhr; //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去 if (xhrOnProgress.onprogress && xhr.upload) { xhr.upload.onprogress = xhrOnProgress.onprogress; } return xhr; } } $.ajax({ url: "/Interface/DealAlarm", type: 'POST', data: formData, // 告诉jQuery不要去处理发送的数据 processData: false, // 告诉jQuery不要去设置Content-Type请求头 contentType: false, //beforeSend: function () //{ // console.log("正在进行,请稍候"); //}, xhr: xhrOnProgress(function (evt) { var percent = Math.floor(evt.loaded / evt.total * 100);//计算百分比 $(".progress-bar-plan").css("width", percent + "%"); $(".progress-bar-font").html(percent + '%'); if (percent == 100) { $(".progress-bar-plan").css("background-color", "#0bae27"); } ////console.log(percent); //// 设置进度条样式 //$('#jdt').css('width',percent * 3 + 'px'); //$('#jdt').css('background','skyblue'); ////显示进度百分比 //$('#jdt').text(percent+'%'); //$('#loaded').text(evt.loaded/1024 + 'K'); //$('#total').text(evt.total/1024 + 'K'); }), success: function (response) { var result = JSON.parse(response); if (result.Code == 0) { history.go(-2); } else { alert(result.Message); } }, error: function (responseStr) { console.log("error"); } }); })