这是一个图片上传的进度条的功能代码,具体图片上传功能,我就不写了,因为本身是已做好现成的上传功能,因为考虑到手机端上传大图片,会有上传延时,不能及时体现上传进度造成体验不好,所以写了段上传进度监听,展示当前图片的上传情况。
前端页面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>