当接口不反对批量上传,应用递归实现单文件上传,配合 mui.loading 实现上传进度
var imgAppendixArr = [];// 以后已上传的图片信息数组,可传递给后端
// 多张图片递归上传
function uploadList(obj, i) {var fileList = $("#" + obj.inputId)[0].files;
var i = i || 0;// 初始为 0,如 i 超过数组的下标阐明已全副上传实现
mui.showLoading("正在上传.. (" + (i + 1) + "/" + fileList.length + ")",
"div"
);
if (i > fileList.length - 1) {mui.hideLoading();
msg("上传实现!");
mui.hideLoading();
return;
}
// 用 formDate 对象上传
var fd = new FormData();
fd.append(obj.data, fileList[i]);
submitPicture(obj.upUrl, fd, function (bat) {bat = JSON.parse(bat);
bat.imgName=fileList[i].name;
bat.imgSrc=getObjectURL(fileList[i]);
bat.imgFile=fileList[i];
obj.cb(bat, obj.filesArr.length);// 图片上传胜利时执行回调函数,并传递以后胜利的图片下标
++i;
uploadList(obj, i);
});
}
function getObjectURL {// 返回长期图片预览门路}
function submit(data, cb) {
$.ajax({
type: "post",
url: 'xxxxx',
data: data,
success: function (data) {cb(data);
},
});
}
// 批量单张图片文件上传
function imgUploadSingle(obj) {
var oInput = "#" + obj.inputId;
$(oInput)
.unbind()
.on("change", function () {var fileImg = $(oInput)[0];
var fileList = fileImg.files;
if (fileList.length > obj.num - obj.filesArr.length) {msg("上传失败,超过限度 ( 附件只能上传" + obj.num + "张图片)");
return false;
}
uploadList(obj);
});
}
imgUploadSingle({
inputId: "image", //input 框 id
upUrl: 'xxxxxx', // 提交地址
data: "file", // 参数名
num:5, // 上传个数
filesArr: imgAppendixArr,
cb: function (bat, i) {if (bat.code == "0") {
imgAppendixArr.push({
name: bat.imgName,
url: bat.data.path,
});
var imgDom =
'<div class="img-box"> <img onclick="imgDisplay(this)"alt="' +
bat.imgName +
'"src="' +
bat.imgSrc +
'"width="100%"height="100"/><div class="img-del"onclick="removeUploadimg(this,' +
i +
')"><span class="mui-icon mui-icon-closeempty" ></span></div></div>';
$(".handle-img-list").append(imgDom); // 增加图片预览
$("#img-sum").text(imgAppendixArr.length);
if (imgAppendixArr.length == 5) {
// 如图片数足够则暗藏上传按钮
$(".xxx").hide();}
} else {mui.hideLoading();
}
},
});