1. 程式人生 > >深入學習jquery原始碼之上傳附件外掛的實現

深入學習jquery原始碼之上傳附件外掛的實現

深入學習jquery原始碼之上傳附件外掛的實現

/**
 * 上傳附件通用JS (基於layerUI)
 */
;(function($){
	var defaults = {
			url : "/attach/upload",		
	    	fieldCode : "aboutDocument",						//業務欄位編碼
	    	fieldName : "相關檔案",								//業務欄位名稱
	    	entityName : "template",							//業務實體
	};
	
	
	function renderUpload(options){
		this.settings = $.extend({},defaults,options);
		this.settings.elem = "#" + this.settings.fieldCode;
		this.settings.bindAction = "#" + this.settings.fieldCode + "_Action";				//上傳操作按鈕	
		this.settings.layuiUploadPreview = "#"+ this.settings.fieldCode +"_preview";
		this.settings.previewTableBody = "#"+ this.settings.fieldCode +"_Preview_Table";	//上傳預覽表格
		this.init();
	}
	//為函式新增原型鏈上的方法
	renderUpload.prototype = {
		init: function(){
			    var that = this;
				var uploadInst = layui.upload.render({
					    elem: that.settings.elem											//繫結元素
					    ,url: CONTEXT_PATH + that.settings.url 									//上傳介面
					    ,accept:'file'
					    ,data:{																	//上傳引數
					    	"entityName" : that.settings.entityName,							//業務實體
					    	"fieldCode" : that.settings.fieldCode,								//業務欄位編碼
					    	"fieldName" : that.settings.fieldName,								//業務欄位名稱
					    }								
					  	,auto:false												//是否選完檔案後自動上傳	如果設定 false,那麼需要設定 bindAction 引數來指向一個其它按鈕提交上傳
					  	,size:0													//設定檔案最大可允許上傳的大小,單位 KB。不支援ie8/9;	0(即不限制)
					  	,multiple:true
					  	//是否允許多檔案上傳。設定 true即可開啟。不支援ie8/9
					  	,bindAction: that.settings.bindAction					//指向一個按鈕觸發上傳,一般配合 auto: false 來使用。值為選擇器或DOM物件,如:bindAction: '#btn'
					    ,choose: function(res){									//選擇檔案後的回撥函式
					    	var layIndex = layer.open({
					        	type: 1,
					        	title: "預覽",
					        	maxmin: false,
					        	area : ['40%', '40%'],
					        	content:$(that.settings.layuiUploadPreview).removeAttr('style'),			//$.loadHtml(preUrl),
					        	success: function(layero){
					        		var demoListView = $(that.settings.previewTableBody).empty();
					        		var files = that.settings.selfFiles = res.pushFile(); //將每次選擇的檔案追加到檔案佇列
					        	      //讀取本地檔案
					        		res.preview(function(index, file, result){
					        	        var tr = $(['<tr id="upload-'+ index +'">'
					        	          ,'<td>'+ file.name +'</td>'
					        	          ,'<td>'+ (file.size/1024).toFixed(1) +' kb</td>'
					        	          ,'<td name="upload-status">等待上傳</td>'
					        	          ,'<td>'
					        	            ,'<button class="layui-btn layui-btn-mini demo-reload layui-hide">重傳</button>'
					        	            ,'<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">刪除</button>'
					        	          ,'</td>'
					        	        ,'</tr>'].join(''));
					        	        
					        	        //單個重傳
					        	        tr.find('.demo-reload').on('click', function(){
					        	        	res.upload(index, file);
					        	        });
					        	        
					        	        //刪除
					        	        tr.find('.demo-delete').on('click', function(){
					        	        	
						        	        delete files[index]; //刪除對應的檔案
						        	        tr.remove();
						        	        uploadInst.config.elem.next()[0].value = ''; //清空 input file 值,以免刪除後出現同名檔案不可選
						        	        if(Object.getOwnPropertyNames(files).length == 0){			//當上傳預覽沒有檔案時,關閉彈出框
						        	        	 layer.close(layIndex);
						        	        }
					        	        });
					        	        demoListView.append(tr);
					        	      });
					        	},
					        	end : function(){	//layer銷燬回撥
					        		$(that.settings.layuiUploadPreview).attr('style','display:none;');
					        		$(that.settings.previewTableBody).empty();
					        	},
					        	cancel: function(){ 		  //右上角關閉回撥
					        	}
					        });
					    	
					    }
					  	,before: function(res){					//檔案提交上傳前的回撥
					  		$("tr",$(that.settings.previewTableBody)).find("td[name='upload-status']").text("上傳中...");
					  	}
					    ,done: function(res, index, upload){					//執行上傳請求後的回撥。返回三個引數,分別為:res(服務端響應資訊)、index(當前檔案的索引)、upload(重新上傳的方法,一般在檔案上傳失敗後使用)
					    	//上傳完畢回撥		"dealPicture_list_table"
					    	if(res && res.status == WebConst.SUCCESS){
					    		$(that.settings.bindAction).text("").text("上傳成功");
					    		delete that.settings.selfFiles[index];
					    		//改變預覽狀態,將上傳附件id存在	隱藏域中
					    		$("tr[id='upload-"+ index +"']",$(that.settings.previewTableBody)).find("td[name='upload-status']").text("附件快取完畢,請點選提交上傳附件");
					    		var unupload = $("#uploadAttachmentIds").data("uploadAttachmentIds");
					    		if(unupload){
					    			unupload.push(res.data['attachmentId']);
					    			$("#uploadAttachmentIds").data("uploadAttachmentIds",unupload);
					    		}else{
					    			if(res.data){
					    				$("#uploadAttachmentIds").data("uploadAttachmentIds",[res.data['attachmentId']]);
					    				/**
					    				 * 第一個方法賦不了值,通過下面的賦值
					    				 */
					    				$("#uploadAttachmentIds").val([res.data['attachmentId']]);
					    			}
					    		}
					    		
					    		//處理卡片頁面列表展示問題
					    		var afile = res.data;
					    		var attachImg = "";
					    		if(!$.isEmptyStr(afile.fileName) && (afile.fileName.indexOf('docx')!=-1 
										 || afile.fileName.indexOf('doc')!=-1))
								 {
									 //attachImg = '<td><img src="' + CONTEXT_PATH +"platform/common/images/word.png" /></td>';
									 attachImg = '<td><img src="'+CONTEXT_PATH+ '/platform/common/images/word.png"' +'width="100" height="60" style="cursor:pointer;"/></td>';
								 }
								 else if(!$.isEmptyStr(afile.fileName) && afile.fileName.indexOf('pdf')!=-1)
								 {
									 attachImg = '<td><img src="'+CONTEXT_PATH+ '/platform/common/images/pdf.png"' +'width="100" height="60" style="cursor:pointer;"/></td>';
								 }
								 else
								 {
									 attachImg = '<td><img src="' + CONTEXT_PATH + '/attach/showPicture?attachmentId=' 
					          		 + afile.attachmentId + '&isThumbnail=true" max-width="120" width="100" height="60" style="cursor:pointer;"/></td>';
								 }
					    		var $tr = $(['<tr id="upload-'+ afile.attachmentId +'" attatchmentId="'+ afile.attachmentId +'">'
							          , attachImg
							          ,'<td>'+ afile.fileName +'</td>'
							          ,'<td>'+ afile.fileSize +' kb</td>'
							          ,'<td>'+ afile.createDate +'</td>'
							          ,'<td>'
							            ,'<a class="layui-btn layui-btn-mini demo-reload" href="'+  CONTEXT_PATH +'/attach/download?attachmentId='+ afile.attachmentId +'">下載</a>&nbsp;&nbsp;'
							            ,'<button class="layui-btn layui-btn-mini layui-btn-danger">刪除</button>'
							          ,'</td>'
							        ,'</tr>'].join(''));
								  	$tr.find('button').on('click',function(){
								  		var attId = $(this).closest("tr").attr('attatchmentId');
								  		var url = CONTEXT_PATH + '/attach/delete/datafile';
								  		var rlt = $.getData(url,{'attachmentIds':attId});
										if(rlt && rlt.status == WebConst.SUCCESS){
											  $(this).closest("tr").remove();
											  $("#uploadAttachmentIds").data("uploadAttachmentIds").removeByValue(attId);
										  }
										return false;
								  	});
								  $("#" + afile.fieldCode + "_list_table").append($tr);
					    	}
					    }
				    ,error: function(index, upload){						//執行上傳請求出現異常的回撥(一般為網路異常、URL 404等)。返回兩個引數,分別為:index(當前檔案的索引)、upload(重新上傳的方法)
				      //請求異常回調
				    }
				});
			}
	}
	
	//擴充套件jquery類方法
	$.extend({
		renderUpload : function(options){
			return new renderUpload(options);
		}
	});
})(jQuery);


如何使用:

                 //執行例項
		$.renderUpload({
			fieldName : "上傳附件",							//業務欄位名稱
	    	fieldCode : "dealPicture",						//業務欄位編碼
	    	entityName : "add",						//業務實體
	    	selfFiles : _self.files
		});