Last active
December 14, 2015 03:18
-
-
Save pinzolo/42dd7f2cf693989ca46e to your computer and use it in GitHub Desktop.
jQuery使ってAJAXでドラッグアンドロップによるファイルアップロード。主にRails用
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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