Created
December 13, 2012 01:26
-
-
Save k-ishiwata/4273263 to your computer and use it in GitHub Desktop.
HTML5のFile API サンプル
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
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="utf-8"> | |
<title>File API Sample</title> | |
<style type="text/css"> | |
#file-input div.input { | |
padding: 60px; | |
border: solid 1px #333; | |
width: 300px; | |
height: 200px; | |
} | |
</style> | |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> | |
<script type="text/javascript"> | |
$(function() { | |
var inEle = $('#file-input div.input'), | |
outEle = $('#file-input div.out'); | |
// ドラッグで画面遷移させない | |
inEle | |
.on('dragenter', function(e) { | |
e.preventDefault(); | |
}) | |
.on('dragover', function(e){ | |
e.preventDefault(); | |
}) | |
.on('drop', function(e){ | |
e.preventDefault(); | |
var files = e.originalEvent.dataTransfer.files; | |
// 画像表示 | |
for (var i=0; i<files.length; i++) { | |
if (files[i].type.match('image.*')) { | |
var reader = new FileReader(); | |
//エラー処理 | |
reader.onerror = function(e) { | |
console.log('error', e.target.error.code); | |
} | |
//読み込み後の処理 | |
reader.onload = function(e){ | |
outEle.append('<img src="'+e.target.result+'" />'); | |
}; | |
reader.readAsDataURL(files[i]); | |
} | |
} | |
// テキスト表示 | |
/* | |
for (var i=0; i<files.length; i++) { | |
if (files[i].type === 'text/plain') { | |
var reader = new FileReader(); | |
//エラー処理 | |
reader.onerror = function(e) { | |
console.log('error', e.target.error.code); | |
} | |
//読み込み後の処理 | |
reader.onload = function(e){ | |
$('<div></div>').text(e.target.result).appendTo(outEle) | |
}; | |
reader.readAsText(files[i], 'shift-jis'); | |
} | |
} | |
*/ | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<p>ファイルをドロップしてください。</p> | |
<div id="file-input"> | |
<div class="input"></div> | |
<div class="out"></div> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment