插件名: jquery.upload.js
基本:
依赖:jquery,ajaxFileUpload.js
调用:$("#uploadBtn").upload(options)
作者:vuturn
Options参数
uploadFile
选择触发的文本上传按钮
callback
回调函数
url
异步请求的url
调用
HTML:
<button id="uploadBtn">文件上传</button> <input type="file" id="uploadFile" name="uploadFile" style="display: none">JS:
$("#uploadBtn").upload({ uploadFile : $("#uploadFile"),callback : function (rs) { console.log(rs); },url:"?r=test/manage" });
说明
1.后台必须返回json,否则ajaxFileUpload会报错
2.修复了文本输入框第二次调用onchange事件失败的bug
jquery.upload.js源代码
;(function ($,window,document,undefined) { //默认操作 var defaults = { //选择元素 uploadFile: $("#uploadFile"),//回调函数 callback: function (rs) { console.log(rs); },//url url: "" },//缓存实例 _that,//插件构造函数 Plugin = function (element,options) { this.element = element; this.options = $.extend({},defaults,options); this._defaults = defaults; this.init(); }; //初始化函数 Plugin.prototype.init = function () { _that = this; //点击上传触发隐藏的文本上传按钮 $(this.element).on("click",function () { //ajaxFileUpload 会自己建立一个隐藏的文本上传按钮,而且将我们的绑定事件转移到这个元素身上 // 所以trigger触发会遇到第二次上传不触发onchange事件 $(_that.options.uploadFile.selector).trigger("click"); }); //文件上传onchange事件 this.options.uploadFile.on("change",function () { DialogBindUploadFile($(this),_that.options.url,_that.options.callback); }); }; //插件 $.fn.upload = function (options) { return this.each(function () { if (!$.data(this,"upload")) { $.data(this,"upload",new Plugin(this,options)); } }); }; var DialogBindUploadFile = function ($obj,url,callback) { var _name = $obj.val(); if (_name) { _name = _name.split("\\").pop(); DialogUploadFile(url,$obj,$obj.attr('id'),_name,"cover",callback); } else { alert("请选择文件"); } },//调用ajaxFileUpload DialogUploadFile = function (_url,_obj,_id,type,success) { var $csrf = $('Meta[name = YII_CSRF_TOKEN]').attr('value'),_data = {}; _data['YII_CSRF_TOKEN'] = $csrf; _data['type'] = type; $.ajaxFileUpload({ url: _url,secureuri: false,fileElementId: _id,dataType: 'json',data: _data,success: function (rs) { //回调函数 success.call(null,rs); //第二次绑定 $(_that.options.uploadFile.selector).on("change",function () { DialogBindUploadFile($(this),_that.options.callback); }); } }); }; })(jQuery,document);