這是一個圖片上傳的進度條的功能代碼,具體圖片上傳功能,我就不寫了,因為本身是已做好現成的上傳功能,因為考慮到手機端上傳大圖片,會有上傳延時,不能及時體現上傳進度造成體驗不好,所以寫了段上傳進度監聽,展示當前圖片的上傳情況。
前端頁面html代碼:
<asp:HiddenField ID="hidnIndexValue" runat="server" Value="0" />
<div>
<img src="/images/bg.png" class="imgSrc">
<input type="file" name="chooseImage" data-txt="hfFileList" id="chooseImage" accept="image/*">
</div>
<div id="percentage"></div>
前端jquery代碼:
<script type="text/javascript">
function shwoProgress(index,total,loaded) {
var width = Math.round(loaded / total * 100) + "%";
$("#percentage").html("<div style='line-height:24px;color:#138edc;font-size:0.38rem;'>正在上傳第" + (index + 1) + "個文件,上傳進度:" + width + "</div>");
}
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;
}
}
$(function(){
$('#chooseImage').on('change', function () {
if ($(this).val() != "")
{
var d = $(this);
var c = $(this).attr("data-txt");
$(this).before($(this).clone(true));
$("#uploadForm input").remove();
$("#uploadForm").append($(this));
$("#uploadForm").append($("<input>", { type: "text", val: c }).attr("name", "fieldName"));
$("#uploadForm").ajaxSubmit({
dataType: "json",
success: function (b) {
var index = parseInt($("#hidnIndexValue").val());
index = index + 1;
$("#hidnIndexValue").val(index);
$("#percentage").html("");
if (b != undefined && b != null) {
if (b.code == 0) {
alert(b.message)
}
else {
alert(b.message)
}
}
},
xhr: xhrOnProgress(function (e) {
var index = parseInt($("#hidnIndexValue").val());
shwoProgress(index, e.total, e.loaded);
})
})
}
});
});
</script>