這個控件功能還不錯,但是對於外部調用上傳有點壓力。
比如說,他可以實現在添加一個文件后為文件添加一個上傳按鈕,這個是寫在add中的,可以調用data.submit()提交數據
但是如果我要實現外部按鈕點擊時觸發這個data.submit()就有壓力了。
有兩種方式:
1、想辦法保存data,在外部事件觸發時,調用到這個data並submit。
2、想辦法為該外部按鈕在add時注冊一個事件,並在點擊時觸發這個事件后submit()
3、生成一個隱藏button,在外部事件觸發時,調用這個button.click()即可。但是要注意重復綁定的問題,要先清除一下事件。
(典型應用,一個表單中有一個上傳輸入框,我想調用這個上傳輸入框的進度事件,用默認的提交有點不方便,就需要使用這個控件,但是在使用控件后,提交時就會因為控件的原因,要么提交后取不到文件(加入add,submit等之后),要么能上傳,但是進度無事件(不加任何屬性))。
現在的要求是,點擊外部上傳按鈕,調用這個控件來上傳。
研究upload-ui源碼后,發現他是調用了jQuery.data來保存對象,相當於第一種方法:
add: function (e, data) { if (e.isDefaultPrevented()) { return false; } var $this = $(this), that = $this.data('blueimp-fileupload') || $this.data('fileupload'), options = that.options; data.context = that._renderUpload(data.files) .data('data', data) //這里把數據綁定進去 .addClass('processing'); options.filesContainer[ options.prependFiles ? 'prepend' : 'append' ](data.context); that._forceReflow(data.context); that._transition(data.context); data.process(function () { return $this.fileupload('process', data); }).always(function () { data.context.each(function (index) { $(this).find('.size').text( that._formatFileSize(data.files[index].size) ); }).removeClass('processing'); that._renderPreviews(data); }).done(function () { data.context.find('.start').prop('disabled', false); if ((that._trigger('added', e, data) !== false) && (options.autoUpload || data.autoUpload) && data.autoUpload !== false) { data.submit(); } }).fail(function () { if (data.files.error) { data.context.each(function (index) { var error = data.files[index].error; if (error) { $(this).find('.error').text(error); } }); } }); },
這里綁定事件
_initEventHandlers: function () { this._super(); this._on(this.options.filesContainer, { 'click .start': this._startHandler, 'click .cancel': this._cancelHandler, 'click .delete': this._deleteHandler }); this._initButtonBarEventHandlers(); },
這里是事件:
_startHandler: function (e) { e.preventDefault(); var button = $(e.currentTarget), template = button.closest('.template-upload'), data = template.data('data'); button.prop('disabled', true); if (data && data.submit) { data.submit(); } },
取到其中的data並提交。
其實也可以調用send方法來發送,但是send方法的參數要求較高,
$('#fileupload').fileupload('send', {files: filesList});
要求參數filesList為 an object with an array (or array-like list) of File or Blobobjects as files property.
同樣添加時也可以直接添加文件列表,並可同時覆蓋一部分屬性
$('#fileupload').fileupload('add', {files: filesList, url: '/path/to/upload/handler.json'});
Retrieving overall progress data
var overallProgress = $('#fileupload').fileupload('progress');