layui upload.js原代碼
Class.prototype.upload = function (files, type) { var that = this , options = that.config , elemFile = that.elemFile[0] //高級瀏覽器處理方式,支持跨域 , ajaxSend = function () { var successful = 0, aborted = 0 , items = files || that.files || that.chooseFiles || elemFile.files , allDone = function () { //多文件全部上傳完畢的回調 if (options.multiple && successful + aborted === that.fileLength) { typeof options.allDone === 'function' && options.allDone({ total: that.fileLength , successful: successful , aborted: aborted }); } }; layui.each(items, function (index, file) {//每個文件進行一次下面的操作,放入formData里,用通過ajax進入后台中上傳處理 var formData = new FormData(); formData.append(options.field, file);//options.field是渲染upload時設置的可上傳的類型, accept: 'file',所以這里options.field是一個固定的值
// debugger; //追加額外的參數 layui.each(options.data, function (key, value) { value = typeof value === 'function' ? value() : value; formData.append(key, value); }); //提交文件 var opts = { url: options.url , type: 'post' //統一采用 post 上傳 , data: formData //這里傳的是formData,后台在request.files里接收 , contentType: false , processData: false , dataType: 'json' , headers: options.headers || {} //成功回調 , success: function (res) { successful++; done(index, res); //res是后台定義的json數據,以前的寫法是string json = "{\"code\": 0 ,\"msg\": \"上傳成功\",\"data\":\"\" }";
//所以index對應的都是同一個res(結果),然后進入done()去處理(剛才的說法錯了,因為文件在后台也是單獨處理的,所以每個文件對應的是不同的json) allDone(); } //異常回調 , error: function () { aborted++; that.msg('請求上傳接口出現異常'); error(index); allDone(); } }; //監聽進度條 if (typeof options.progress === 'function') { opts.xhr = function () { var xhr = $.ajaxSettings.xhr(); //監聽上傳進度 xhr.upload.addEventListener("progress", function (e) { if (e.lengthComputable) { //debugger; var percent = Math.floor((e.loaded / e.total) * 100); //百分比 options.progress(percent, options.item[0], e, index); } }); return xhr; } } $.ajax(opts); }); } //低版本IE處理方式,不支持跨域 , iframeSend = function () { var iframe = $('#' + ELEM_IFRAME); that.elemFile.parent().submit(); //獲取響應信息 clearInterval(Class.timer); Class.timer = setInterval(function () { var res, iframeBody = iframe.contents().find('body'); try { res = iframeBody.text(); } catch (e) { that.msg('獲取上傳后的響應信息出現異常'); clearInterval(Class.timer); error(); } if (res) { clearInterval(Class.timer); iframeBody.html(''); done(0, res); } }, 30); } //統一回調 , done = function (index, res) { //每個文件后台處理完后調用done 然后對這個文件判斷是否成功以及前台顯示之類,(這是沒有問題的,啊啊啊,花了一天時間改來改去,原來這個原代碼是對的...) that.elemFile.next('.' + ELEM_CHOOSE).remove(); elemFile.value = ''; if (typeof res !== 'object') { try { res = JSON.parse(res); } catch (e) { res = {}; return that.msg('請對上傳接口返回有效JSON'); } } typeof options.done === 'function' && options.done(res, index || 0, function (files) { that.upload(files); }); } //統一網絡異常回調 , error = function (index) { if (options.auto) { elemFile.value = ''; } typeof options.error === 'function' && options.error(index || 0, function (files) { that.upload(files); }); }