Skip to content

Instantly share code, notes, and snippets.

@aur1mas
Created July 31, 2012 06:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aur1mas/3214304 to your computer and use it in GitHub Desktop.
Save aur1mas/3214304 to your computer and use it in GitHub Desktop.
html5 file uploader
/**
* enables HTML5 file uploader & old style for browsers which don't support
*
* @require filedrop.jquery.js
* @author aur1mas <aurimas@devnet.lt>
*/
jQuery.fn.uploader = function(options) {
var defaults = {
paramname: 'pic',
maxfiles: 5,
maxfilesize: 2
};
var o = jQuery.extend(defaults, options);
return this.each(function() {
var e = jQuery(this);
var message = $('.message', e);
e.filedrop({
paramname: o.paramname,
maxfiles: o.maxfiles,
maxfilesize: o.maxfilesize,
url: o.url,
/* response is the JSON object that post o.url returns */
uploadFinished: function(i, file, response){
$.data(file).addClass('done');
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files! You can upload 15 images in total. Currently you can upload ' + o.maxfiles + ' at most! Delete some uploaded images & try again.');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to ' + o.maxfilesize + ' MB.');
break;
default:
break;
}
},
/* Called before each upload is started */
beforeEach: function(file){
if(!file.type.match(/^image\//)){
alert('Only images are allowed!');
/* Returning false will cause the file to be rejected */
return false;
}
},
uploadStarted: function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
$.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = $(template),
image = $('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
// e.target.result holds the DataURL which
// can be used as a source of the image:
image.attr('src',e.target.result);
};
// Reading the file as a DataURL. When finished,
// this will trigger the onload function above:
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
// Associating a preview container
// with the file, using jQuery's $.data():
$.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
}
$(function() {
$('#dropbox').uploader({
maxfiles: 15,
url: '<?=$this->url(array('controller' => 'info', 'action' => 'photos'), 'default', true)?>'
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment