Skip to content

Instantly share code, notes, and snippets.

@Prinzhorn
Last active December 25, 2015 16:49
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 Prinzhorn/7009257 to your computer and use it in GitHub Desktop.
Save Prinzhorn/7009257 to your computer and use it in GitHub Desktop.
File upload library

I'm currently using https://github.com/blueimp/jQuery-File-Upload, but it's a mess. It does it's job, but the API is...suboptimal.

I took a look at several other solutions, but most of the examples looked like this (which made me cry a little):

$(document).ready(function() {
    $('#some-input').myPlugin({
        option1: 1,
        /*
            A list of thousands of options
        */
    });
});

From the top of my head I'm looking for an API like this (let's call our fictional library zoidberg):

var queue = new zoidberg.UploadQueue({
	url: '/upload',
	max: 3//parallel
});

//Executed for each added file.
//`file` is actually a zoidberg.File instance, which for example emits events.
//e.g. file.on('progress', function() {}) (or 'upload', 'cancelled', 'error', 'done', etc.)
var fileAdded = function(file) {
	//Now accept or reject file, for example based on the extension.
	if(/\.(?:jpe?g|png|gif)/.test(file.name)) {
		queue.add(file);
	} else {
		//Display an error message or whatever you want.
	}
};

new zoidberg.DropTarget('#drop-it-like-its-hot', fileAdded);
new zoidberg.FileChooser('#click-me', fileAdded);

//At this point you have drag & drop working and a old-school file-chooser.
//The zoidberg.UploadQueue can be configured to upload files immediately or not.
//If not, then you need to call `upload` on each zoidberg.File manually.

//Now the cool thing is, if you only need a single file upload, e.g. for a profile pic, then all you need is:
new zoidberg.FileChooser('#click-me', function(file) {
	file.upload('/profile-pic');

	file.on('progress', function() {
		//Display progress
	});

	file.on('error', function() {
		//Handle error
	});

	file.on('success', function() {
		//YAY!
	});
});

//No need to include or use zoidberg.UploadQueue or zoidberg.DropTarget at all.

Why is there no such simple API? Why do most of the libraries rely on jQuery? Why do most of them come with a default, opinionated UI (why not make seperate UI projects which have the library as dependency?)?

I know this ain't Java, but that doesn't mean you need to hide everything behind a single function or class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment