Skip to content

Instantly share code, notes, and snippets.

@dansimco
Created July 13, 2012 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansimco/3106555 to your computer and use it in GitHub Desktop.
Save dansimco/3106555 to your computer and use it in GitHub Desktop.
InstantFileUploader
/*global Element, IFrame, document, Button */
var InstantFileUploader;
InstantFileUploader = function (input, params) {
"use strict";
var self = this;
self.frameId = String.uniqueID();
self.loading = false;
self.onComplete = params.onComplete || function () {};
self.onFailure = params.onFailure || function () {};
self.onRequest = params.onRequest || function () {};
self.input = input.setStyles({
'opacity' : '0',
'z-index' : '2',
'position' : 'relative'
});
self.submit_button = new Element('button', {
'text' : 'Select File',
'styles' : {
'position' : 'absolute',
'top' : '0',
'left' : '0',
'z-index' : '1'
}
});
self.input.addEvent('change', function () {
self.submit_button.click();
});
self.input.addEvents({
'change' : function () {
self.submit_button.click();
},
'mousedown' : function () { self.submit_button.fireEvent('mousedown'); },
'mouseup' : function () { self.submit_button.fireEvent('mouseup'); },
'mouseout' : function () { self.submit_button.fireEvent('mouseout'); },
'mouseleave' : function () { self.submit_button.fireEvent('mouseleave'); }
});
self.submit_button.controller = new Button(self.submit_button, {
preventDefault : false,
click : function () {
self.loading = true;
self.submit_button.set('text', 'Uploading ...');
self.onRequest();
}
});
self.form = new Element('form', {
'accept-charset' : 'utf-8',
'enctype' : 'multipart/form-data',
'method' : 'post',
'target' : self.frameId,
'action' : input.get('data-action'),
'styles' : {
'position' : 'relative'
}
});
self.form.inject(self.input, 'after').adopt([self.input, self.submit_button]);
self.iframe = new IFrame({
name : self.frameId,
styles : { display : 'none' },
src : 'about:blank',
events : {
load : function () {
if (self.loading) {
var doc = this.iframe.contentWindow.document;
self.submit_button.set('text', 'Select File');
if (doc && doc.location.href !== 'about:blank') {
self.onComplete(doc.body.innerHTML);
} else {
self.onFailure();
}
self.loading = false;
}
}.bind(this)
}
}).inject(document.body);
return self;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment