Skip to content

Instantly share code, notes, and snippets.

@kazukgw
Created December 9, 2012 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazukgw/4245287 to your computer and use it in GitHub Desktop.
Save kazukgw/4245287 to your computer and use it in GitHub Desktop.
FileAPI & FileReaderAPI #js
/*
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
以下でFileを選択するとbody に imgタグがappendされる
<input type="file" id="files" />
</body>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="./script.js"></script>
<script>
window.onload = function(){ if( window.File ) {main(); } else {alert('the file apis are not fully supported in this browser.'); } }
</script>
</html>
*/
/******************* JavaScript ****************************/
var main = function main(){
///////////////////////////////////////////////////////////////
function handleFileSelect(evt) {
//fileList API は 以下で設定
//イベントオブジェクトの中にふくまれている!!
var files = evt.target.files; // FileList object
//FileReaderとか File とかの APIは windowオブジェクトが親になる
var reader = new FileReader();
//reader.onload で画像読み込み後にこの以下の処理を行うように指定
reader.onload = function(e) {
alert("hoge");
$("body").append('<img src="'+ e.target.result +'"/>');
};
for(var i = 0; i < files.length; i++ ){
reader.readAsDataURL(files[i]);
}
}
$('#files').bind('change', handleFileSelect);
///////////////////////////////////////////////////////////////
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment