シンプルな画像のドラッグ アンド ドロップ jquery 拡張機能を作成しています。1 つのファイルをドラッグすると、ファイルのプレビューが表示され、ファイル名と ajax POST 経由で送信される画像データを含むオブジェクトが返されます。
(function($) {
$.fn.dnd = function()
{
jQuery.event.props.push('dataTransfer');
$(this).bind('drop',function(e){
var files = e.dataTransfer.files;
var $preview = $(this);
var result = [];
if(files.length > 1)
{
$(this).html('One file only');
return false;
}
if(files[0].type === 'image/png' ||
files[0].type === 'image/jpeg' ||
files[0].type === 'image/ppeg')
{
var fileReader = new FileReader();
fileReader.onload = (function(f)
{
return function(e)
{
result.push({name:f.name,value:this.result});
$preview.removeAttr('style');
$preview.html('<img src="'+ this.result +'" width="80%"/>');
};
})(files[0]);
fileReader.readAsDataURL(files[0]);
}
else
{
$(this).html('images only. GIF not allowed.');
return false;
}
e.preventDefault();
return result;
});
};
}(jQuery));
この方法でコードを実行します。
$(document).ready(function(){
var result = $('#ec-drag-n-drop').dnd();
console.log(result);
}
コンソールを見ると、「未定義」が返されます。何か不足していますか?