當接口不支持批量上傳,使用遞歸實現單文件上傳,配合mui.loading實現上傳進度ajax
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(); } }, });