UploadButton или загрузка файла по нажатию
Однажды понадобился мне плагин для загрузки файла, перерыл интернет, но так и не нашел то что мне надо.
После долгого изучения найденных плагинов написал свой.
(function ($) { function log(msg) { if (console && console.log) { console.log("upload button: " + msg); } } $.fn.uploadButton = function (settings) { var config = $.extend({ url: "index.php", maxFileSize : 2097152, dataType: "html", name: "uploadfile", change: $.noop, success: $.noop }, settings); var $button, $input, $wrap, $form; function init(el) { $button = $(el); $button.button() .bind('mouseenter', function () { $wrap.css("visibility", "visible"); }); $input = $("<input />", { type : "file", name : config.name, autocomplete : "off", css : { fontSize : '600px', position : "absolute", right : 0, margin : 0, padding : 0 } }).bind('change', function () { var val = $(this).val().replace(/.*(\/|\\)/, ""); var ext = val.toLowerCase(); ext = ext.split("."); ext = ext[ext.length-1]; if(config.change(val, ext)){ $form.ajaxSubmit({ dataType: config.dataType, success: config.success }); }; }).appendTo( $form = $("<form />", { action : config.url, method : "post", enctype : "multipart/form-data" }).appendTo( $wrap = $('<div />', { css : { position : "absolute", visibility : "hidden", overflow : "hidden", zIndex : 100000, opacity : 0, left : 0, top : 0, width : $button.get(0).offsetWidth, height : $button.get(0).offsetHeight, margin : 0, padding : 0, direction : "ltr" } }).bind('mouseout', function () { $wrap.css("visibility", "hidden"); }) .appendTo($button.get(0)) ) ); $("<input />", { name : "MAX_FILE_SIZE", value : config.maxFileSize, type: "hidden" }).appendTo($form); } this.each(function () { try { init(this); } catch (e) { log(e); } }); return this; }; }(jQuery));
Плагин использует jQueryUI и jquery.form.
Вызвать его очень просто:
<span id="upl">Upload</span> <script type="text/javascript"> jQuery(function() { $("#upl").uploadButton({ url: "index.php", maxFileSize: 2097152, dataType: "html", name: "uploadfile", success: function(msg) { alert(msg); }, change: function(msg) { alert(msg); return true; } }); }); </script>
Пояснение к опциям:
url — то же что и action у форм
maxFileSize — скрытое поле MAX_FILE_SIZE
dataType — Тип возвращаемого ответа
name — Название элемента input
success — Функция обработки ответа
change — Функция срабатывающая при выборе файла. На входе содержит имя файла. Чтобы прервать отправку нужно вернуть false
Демонстрация
Популярность: 10%
Смотреть еще по теме:
Понравилась заметка? Подписывайся на RSS
