19 апреля 2011 г.

Plupload. Удобный загрузчик файлов.


Все разработчики рано или поздно сталкиваются с необходимостью разрешить пользователям загружать файлы на сервер. Способов решения существует великое множество, но в этой статье я ограничусь лишь одним. Это Plupload.

Ниже описывается работа с версией 1.4.3.2.
Офф. сайт: www.plupload.com
Скачать можно отсюда
API

Подключаем JS на страницу:
<script src="plupload/js/plupload.full.js">
</script>
<script src="plupload/js/jquery.plupload.queue/jquery.plupload.queue.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js">
</script>
CSS:
... src="plupload/js/jquery.ui.plupload/css/jquery.ui.plupload.css" ...
... src="plupload/js/jquery.plupload.queue/css/jquery.plupload.queue.css" ...
Пишем в <head>:
$(function(){
$("#elem").pluploadQueue({
runtimes : 'gears,flash,silverlight,html5',
url : 'includes/fnc/horo/upload.php',
max_file_size : '1mb',
unique_names : false,
dragdrop : false,
multi_selection : false,
multiple_queues : true,
flash_swf_url : '/plupload/js/plupload.flash.swf',
silverlight_xap_url : '/plupload/js/plupload.silverlight.xap',
filters : [
{title : "Text files", extensions : "txt"}
],
// PreInit events, bound before any internal events
preinit : {
// Вызывается при инициализации объекта
Init: function(up, info) {
var title = 'Horoskope [Initialized with '+info.runtime+']';
$('#horo').dialog({title:title});
up.features.progress = true;
up.features.chunks = false;
up.features.dragdrop = false;
up.features.jpgresize = false;
up.features.pngresize = false;
up.features.multipart = true;
console.log(up);
},
// Событие происходит при завершении закачки файла
UploadFile: function(up, file) {
//file.id - Уникальный идентификатор  файла
//file.loaded - Отображает количество загруженных байтов
//file.name - Имя файла на стороне клиента
//file.size - Полный размер файла в байтах
//file.percent - Загруженные проценты
//***********************************************************************//
// Перед отправкой файла на сервер можно переписать параметры.
// Например изменить путь файла обработчика
// или добавить параметры для отправки вместе с запросом
//***********************************************************************//
// up.settings.url = 'upload.php?id=' + file.id;
// up.settings.multipart_params = {param1 : 'value1', param2 : 'value2'};
}
},
// Post init events, bound after the internal events
init : {
Refresh: function(up) {
// Called when upload shim is moved
//console.log('[Refresh]');
},
StateChanged: function(up) {
// Called when the state of the queue is changed
//console.log('[StateChanged]'+(up.state == plupload.STARTED ? "STARTED" : "STOPPED"));
},
QueueChanged: function(up) {
// Called when the files in queue are changed by adding/removing files
//console.log('[QueueChanged]');
},
UploadProgress: function(up, file) {
// Called while a file is being uploaded
//console.log('[UploadProgress...]');
//console.log(file);
//console.log(up);
},
FilesAdded: function(up, files) {
// Callced when files are added to queue
//var o = new Object();
//plupload.each(files, function(file) {
// o[file.name] = {'name':file.name,'size':file.size+' bytes'};
//});
//console.log(o);
},
FilesRemoved: function(up, files) {
// Called when files where removed from queue
//console.log('[FilesRemoved]');
//var o = new Object();
//plupload.each(files, function(file) {
// o[file.name] = {'name':file.name,'size':file.size+' bytes'};
//});
//console.log(o);
},
FileUploaded: function(up, file, info) {
// Called when a file has finished uploading
//console.log('[FileUploaded]...');
//console.log(file);
//console.log(info);
},
ChunkUploaded: function(up, file, info) {
// Called when a file chunk has finished uploading
//console.log('[ChunkUploaded] File:'+file+", Info:"+info);
},
Error: function(up, args) {
// Called when a error has occured
//console.log('[error...]');
//console.log(args);
}
}
});
});

Комментариев нет:

Отправить комментарий