当接口不支持批量上传,使用递归实现单文件上传。
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();
}
},
});