szurubooru/public_html/js/Controls/FileDropper.js

66 lines
1.6 KiB
JavaScript
Raw Normal View History

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-25 18:47:44 +02:00
var options = {
onChange: null,
setNames: false,
};
var $dropDiv = jQuery('<div class="file-handler"></div>');
var allowMultiple = $fileInput.attr('multiple');
$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) {
addFiles(this.files);
});
2014-09-07 09:57:01 +02:00
$dropDiv.on('dragenter', function(e) {
$dropDiv.addClass('active');
2014-09-07 09:57:01 +02:00
}).on('dragleave', function(e) {
$dropDiv.removeClass('active');
2014-09-07 09:57:01 +02:00
}).on('dragover', function(e) {
e.preventDefault();
2014-09-07 09:57:01 +02:00
}).on('drop', function(e) {
e.preventDefault();
addFiles(e.originalEvent.dataTransfer.files);
2014-09-07 09:57:01 +02:00
}).on('click', function(e) {
$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.');
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-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
};