Skip to content

Instantly share code, notes, and snippets.

@pinzolo
Last active December 14, 2015 03:18
Show Gist options
  • Save pinzolo/42dd7f2cf693989ca46e to your computer and use it in GitHub Desktop.
Save pinzolo/42dd7f2cf693989ca46e to your computer and use it in GitHub Desktop.
jQuery使ってAJAXでドラッグアンドロップによるファイルアップロード。主にRails用
<div id="drop-area" class="file-drop-area">
<input id="upload-file" type="file" class="hidden"/>
<button id="select-file" class="btn btn-primary">ファイルを選択</button>
</div>
jQuery(document).ready(function($) {
var cancel = function(e) {
e.preventDefault();
e.stopPropagation();
return false;
};
$('.file-drop-area').bind('dragenter', function(e) {
$(this).addClass('drag-enter');
return cancel(e);
}).bind("dragleave", function(e) {
$(this).removeClass('drag-enter');
return cancel(e);
}).bind('dragover', function(e) {
return cancel(e);
}).bind('drop', function(e) {
$(this).removeClass('drag-enter');
return cancel(e);
});
});
jQuery(document).ready(function($) {
var uploadFile = function(file) {
formData = new FormData();
formData.append('file', file);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false
}).done(function(data, status, response) {
console.log('success');
}).fail(function(response, status, thrown) {
console.log(response.responseText);
});
};
$('#drop-area').bind('drop', function(e) {
if (e.originalEvent.dataTransfer.files.length > 0) {
uploadFile(e.originalEvent.dataTransfer.files[0]);
}
});
$('#upload-file').bind('change', function() {
if (this.files.length > 0) {
uploadFile(this.files[0]);
}
});
$('#select-file').bind('click', function() {
$('#upload-file').click();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment