2014-09-07 00:33:46 +02:00
|
|
|
var App = App || {};
|
|
|
|
App.Controls = App.Controls || {};
|
|
|
|
|
2014-10-05 13:25:40 +02:00
|
|
|
App.Controls.FileDropper = function($fileInput) {
|
|
|
|
var _ = App.DI.get('_');
|
|
|
|
var jQuery = App.DI.get('jQuery');
|
2014-09-07 00:33:46 +02:00
|
|
|
|
2014-09-25 18:47:44 +02:00
|
|
|
var options = {
|
|
|
|
onChange: null,
|
|
|
|
setNames: false,
|
|
|
|
};
|
|
|
|
|
2014-09-07 00:33:46 +02:00
|
|
|
var $dropDiv = jQuery('<div class="file-handler"></div>');
|
2014-09-13 16:09:23 +02:00
|
|
|
var allowMultiple = $fileInput.attr('multiple');
|
2014-09-07 00:33:46 +02:00
|
|
|
$dropDiv.html((allowMultiple ? 'Drop files here!' : 'Drop file here!') + '<br/>Or just click on this box.');
|
|
|
|
$dropDiv.insertBefore($fileInput);
|
|
|
|
$fileInput.attr('multiple', allowMultiple);
|
|
|
|
$fileInput.hide();
|
|
|
|
|
2014-09-07 09:57:01 +02:00
|
|
|
$fileInput.change(function(e) {
|
2014-09-07 00:33:46 +02:00
|
|
|
addFiles(this.files);
|
|
|
|
});
|
|
|
|
|
2014-09-07 09:57:01 +02:00
|
|
|
$dropDiv.on('dragenter', function(e) {
|
2014-09-07 00:33:46 +02:00
|
|
|
$dropDiv.addClass('active');
|
2014-09-07 09:57:01 +02:00
|
|
|
}).on('dragleave', function(e) {
|
2014-09-07 00:33:46 +02:00
|
|
|
$dropDiv.removeClass('active');
|
2014-09-07 09:57:01 +02:00
|
|
|
}).on('dragover', function(e) {
|
2014-09-07 00:33:46 +02:00
|
|
|
e.preventDefault();
|
2014-09-07 09:57:01 +02:00
|
|
|
}).on('drop', function(e) {
|
2014-09-07 00:33:46 +02:00
|
|
|
e.preventDefault();
|
|
|
|
addFiles(e.originalEvent.dataTransfer.files);
|
2014-09-07 09:57:01 +02:00
|
|
|
}).on('click', function(e) {
|
2014-09-07 00:33:46 +02:00
|
|
|
$fileInput.show().focus().trigger('click').hide();
|
|
|
|
$dropDiv.addClass('active');
|
|
|
|
});
|
|
|
|
|
|
|
|
function addFiles(files) {
|
|
|
|
$dropDiv.removeClass('active');
|
|
|
|
if (!allowMultiple && files.length > 1) {
|
2014-09-08 22:02:28 +02:00
|
|
|
window.alert('Cannot select multiple files.');
|
2014-09-07 00:33:46 +02:00
|
|
|
return;
|
|
|
|
}
|
2014-09-25 18:47:44 +02:00
|
|
|
if (typeof(options.onChange) !== 'undefined') {
|
|
|
|
options.onChange(files);
|
|
|
|
}
|
|
|
|
if (options.setNames && !allowMultiple) {
|
|
|
|
$dropDiv.text(files[0].name);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function readAsDataURL(file, callback) {
|
|
|
|
var reader = new FileReader();
|
|
|
|
reader.onloadend = function() {
|
|
|
|
callback(reader.result);
|
|
|
|
};
|
|
|
|
reader.readAsDataURL(file);
|
2014-09-07 00:33:46 +02:00
|
|
|
}
|
2014-09-08 22:02:28 +02:00
|
|
|
|
2014-09-25 18:47:44 +02:00
|
|
|
_.extend(options, {
|
|
|
|
readAsDataURL: readAsDataURL,
|
|
|
|
});
|
|
|
|
|
|
|
|
return options;
|
2014-09-08 22:02:28 +02:00
|
|
|
};
|