Wiki

Clone wiki

GearsUploader / Home

Русская документация

GearsUploader

GearsUploader is a Google Gears-based library with unobtrusive file-input replacement MooTools classes. They features animated progress bar, client-side image resizing, multiple file uploads, complete emulation of traditional form submissions (no server-side changes are required) and Django formset submissions. Full library is < 4KB (yui compressed and gzipped). License is MIT.

How to work with the library

The library depends on Gears browser plugin >= 0.5.21 and MooTools 1.2.2+.

Include one of provided files from GearsUploader/build directory. They are named in this pattern: GearsUploader.<lang>[.compression].js

As usually, use yui-compressed version for production and uncompressed version for debugging. The entire library is < 4Kb (yui-compressed and gzipped).

General information about Gears can be found here: http://code.google.com/intl/ru/apis/gears/design.html

Gears > = 0.5.21 is required. But obsolete versions of Gears is usually not a problem because autoupdate is enabled by default.

function isSupported()
{
    if (!window.google || !google.gears)
        return false;

    if (google.gears.factory.version < '0.5.21')
        return false;

    return true;
}

Individual source files and provided Classes

GearsMultipartForm.js

GearsMultipartForm is the class to emulate html multipart form submissions according to rfc2388. It doesn't require any additional libraries (the rest of the library requires MooTools > = 1.2.2).

Limitation: `multipart/mixed` part or rfc2388 (several files as one form entry) is not implemented. Don't know if it is used anywhere.

Example:

 var desktop = google.gears.factory.create('beta.desktop');
 desktop.openFiles(function(files){
    var form = new GearsMultipartForm({
        files: {'myFile1': files[0]},
        fields: {'myInput': 'value', 'mySelect': ['value1', 'value2']}
    });
    form.post('my_url');
 });

ProgressBar.js

It is a MooTools Class for customizable progress bar written by David Walsh. Documentation can be found here: http://davidwalsh.name/js/progressbar

It is used to create progress bars in other classes. If the progress bar is not needed, you can skip inclusion of this file.

Example

css:

.container {overflow:hidden;}
.clear {clear: both;}

#progress-bar {
    border:1px solid Lavender;
    width:280px;
    height:16px;
    margin: 8px 0px 8px 0px;
    float:left;
}
#progress-bar-box-id {float:left; width: 100%;}
#progress-bar-percentage-id { background: RoyalBlue; height:16px; }
#progress-bar-display-id {color:black; padding-left: 288px;}

html:

<div class='container'>
    <div id='progress-bar'></div>
    <div class='clear'></div>
</div>

js:

var pb = new ProgressBar({
    container:'progress-bar',
    displayText: true,
    speed: 100
});

gears_init.js

Gears init file. More info is here: http://code.google.com/intl/ru/apis/gears/tools.html

GearsUploader.js

Contains 2 MooTools classes: GearsUploader and GearsSingleFileUploader.

Depends on GearsMultipartForm.js.

GearsUploader

The algorithm works as follows:

  1. Initially visible elements are selectHandler and statusElement
  2. The user presses selectHandler, selects 1 or more files
  3. The selected files are processed. By default, they are just added to the list of files to upload. If you want to do something else (for example, display a list files), you need to override the handleFile method (that is what GearsImageUploader does). The simple uploading of files is not elaborated in great detail because I don't need it right now, but customization is not difficult.
  4. When the files are processed, the uploadHandler is displayed.
  5. The user clicks on uploadHandler and submits the form to the server. Progress bar with an upload indication appears.

During all stages the text in statusElement is changing according to current stage. Texts for that can be passed to constructor as `statuses` variable.

For default localized texts one can include file Localization/<lang>.js, which will change all the default texts to different language. English, Russian and Polish translations (en.js, ru.js, pl.js) are supplied. Other translations are welcome.

For each translation there is separate pre-built file in GearsUploader/build folder so you can just pick language you want and don't worry about localization.

Usage

css:

/* ... + styles for ProgressBar, see example above */

#upload-handler{ display: none;}

html:

<input type='button' value='Select files to upload' id='select-handler'>
<input type='button' value='Upload files' id='upload-handler'>

<span id='upload-status'></span>

<div class='container'>
    <div id='progress-bar'></div>
    <div class='clear'></div>
</div>

js:

var pb = new ProgressBar({
    container:'progress-bar',
    displayText: true,
    speed: 100
});

var uploader = new GearsUploader({
    statusElement: 'upload-status',
    progressBar: pb
});

Constructor parameters

  • progressBar: an instance of ProgressBar, default is `null`
  • statusElement: Element (or it's id) which will contain statuses, default is null
  • statuses: dictionary with status messages. For English locale the default is
{
    'noFiles': 'Please select some files to upload.',
    'alreadyUploaded': 'Files was already uploaded.',
    'processing': 'Processing files..',
    'selected': 'Files are selected.',

    'stateUninitialized': 'Initializing..',
    'stateOpen': 'Uploading files..',
    'stateSent': 'Files are uploaded, waiting for server response..',
    'stateInteractive': 'Reading server response..',
    'stateComplete': 'Files are uploaded.'
}

English in not my native language so suggestions here are welcome.

  • verboseProcessing: show more statuses, default is true
  • queueProcessing: emulate sequential rendering by chaining setTimeout calls. Without this some status messages will not be displayed. It is true by default. More information can be found here.
  • uploadHandler: Element (or it's id) by clicking on which uploading begins. By default it is 'upload-handler'.
  • hideUploadHandler: hide uploadHandler when files are not selected. Default is true.
  • selectHandler: Element (or it's id) by clicking on which file selection dialog will be shown. Default is 'select-handler'.
  • fileOpenOptions: options for the `openFiles` function. Check out the feature here. By default {singleFile: false}.
  • url: the address to which the form will be sent. Default is '.'
  • fileElementName: name of the emulated element <input type='file' name='...'> in form. Each name is appended with a file number, starting with 0. By default fileElementName='file'. This means by default files will be available in the $FILES ['file0'], $FILES['file1'], etc. in php, request.FILES['file0'], etc. in django, likewise in other systems. To change the naming algorithm you should override the `getFileElementName` method.
  • formElement: Form element (or it's id). If it is not null then all fields from this form will also be POST'ed.

events: onUploadUninitialized, onUploadOpen, onUploadSent, onUploadInteractive, onUploadComplete. Called in the process of uploading files when requestState is changing. By default, sets the status message. HttpRequest instance is passed to onUploadInteractive and onUploadComplete handlers. onBeforeUpload event is fired just before upload begins. onFileSelect event is fired when user clicks on 'select file' button.

How to customize

QSolution
Run something when uploading state is changedAdd a handler for the event.
Process files before uploadingOverride handleFile.
Add text form fields for each file or just a fewOverride getFormFields.

GearsSingleFileUploader

Usage is the same as GearsUploader, with a few differences:

  • The default status messages are in the singular
  • Does not allow selecting more than 1 file
  • File number is not appended to fileElementName. By default uploaded file will be available as $FILES['file'] or request.FILES['file'].

GearsImageUploader.js

Contains 2 MooTools Classes: GearsImageUploader and GearsSingleImageUploader.

Depends GearsUploader.js and GearsMultipartForm.js.

GearsImageUploader

GearsImageUploader is the same as GearsUploader with some differences:

  • Offers to choose only images (jpeg, png)
  • Ablility to display image previews
  • Ability to resize images before upload
  • Different set of status messages by default
  • fileElementName is 'image' by default, not 'file'

Additional constructor parameters

  • maxWidth: width to resize image to before upload. Default is 600.
  • previewWidth: width of browser-preview. If it is null then thumbnails will use the same resized image that will be sent to the server. It makes sense to set previewWidth != null if the maxWidth parameter is large and thus preview rendering is slow (but this will lead to additional costs of memory and CPU, so set it != null only if necessary and after testing). By default it is null.
  • quality: quality setting for JPEG-encoder, from 0 to 1. Default = 0.9.
  • previewsElement: container element (or it's id). <img> elements for thumbnails will be inserted in that container. Default is 'gears-previews'. Thumbnails can be deleted by clicking on them.

GearsSingleImageUploader

It is a combination of GearsSingleFileUploader and GearsImageUploader. All that written for them is true except one point: previewsElement should indicate not the container in which to insert <img> elements but an existing <img> element. Thumbnail will be shown in this <img> element after file selection. This element won't respond to mouse clicks.

DjangoUploader.js

Contains MooTools Classes (DjangoUploader and DjangoImageUploader) that can emulate Django's Formsets. They can construct formset management form cliend-side. Otherwise they are similar to GearsUploader and GearsImageUploader.

Depends GearsUploader.js and GearsMultipartForm.js. DjangoImageUploader is available only if GearsImageUploader.js is loaded.

DjangoUploader

A subclass of GearsUploader. Constructs formset management form.

Extra constructor parameters

  • FormsetPrefix: formset prefix. By default = 'form', as in Django.

Example

Django view for files uploading:

#models.py
class MyModel(models.Model)
    file = models.FileField()

#forms.py
FormsetCls = modelformset_factory(MyModel)

#views.py
def upload_files(request):
    if request.method == 'POST':
        formset = FormsetCls(request.POST, request.FILES, queryset = MyModel.objects.none())
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect('/')
    else:
        formset = FormsetCls(queryset = MyModel.objects.none())
    return direct_to_template('upload_files.html', {'formset': formset})

(or a more complicated version that saves server resources):

def upload_files(request):
    if request.method == 'POST':
        formset = FormsetCls(request.POST, request.FILES, queryset = MyModel.objects.none())
        if formset.is_valid():
            formset.save()
            if request.is_ajax():
                return HttpResponse()
            return HttpResponseRedirect('/')
        else:
            if request.is_ajax():
                return HttpResponse(formset.errors)
    else:
        formset = FormsetCls(queryset = MyModel.objects.none())
    return direct_to_template('upload_files.html', {'formset': formset})

In both cases `upload_files` view can work both with DjangoUploader and without it.

js - as usual:

var uploader = new DjangoUploader({
    statusElement: 'upload-status',
    progressBar: pb
});

DjangoImageUploader

It is a combination of DjangoUploader and GearsImageUploader. This class is the most suitable for building rich multiple file-uploaders with Django.

Please note that if you want to replace default widget for ImageField in form then you should use GearsSingleImageUploader, not the DjangoImageUploader. DjangoImageUploader is for formsets.

Localization

English, Russian and Polish locales are provided. Pick the file from `build` folder with locale you like. Other translations should be implemented as files in Localization folder similar to en.js.

If you don't use pre-built library version and include source files by hand then in order to use translation you should include translation script after all GearsUploader's scripts but before user code.

Updated