jqueryでローカルファイル(テキストファイル)の読込み

  1. <!DOCTYPE html>
  2. <html lang="ja">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>jqueryでローカルファイル(テキストファイル)の読込み</title>
  6. <script type="text/javascript" src="jquery-1.5.1.min.js"></script>
  7. <script type="text/javascript">
  8.   function handleFileSelect() {
  9.     if (window.File) {
  10.       // File APIが実装のブラウザ
  11.       var fileList = document.getElementById("files").files;
  12.       var reader = new FileReader();
  13.       reader.onload = function(){
  14.         // ファイル読み込み完了時
  15.         $("#list").html(reader.result);
  16.       }
  17.       // ファイルの読込み
  18.       reader.readAsText(fileList[0], "utf-8");
  19.     }
  20.     else {
  21.       // File APIが未実装のブラウザ
  22.       $("#list").html("File APIが未実装のブラウザ");
  23.     } 
  24.   }
  25.   $(document).ready(function () {
  26.     document.getElementById('files').addEventListener('change', handleFileSelect, false);
  27.   });
  28. </script>
  29. </head>
  30. <body>
  31. <h1>jqueryでローカルファイル(テキストファイル)の読込み</h1>
  32. <div>
  33.   <input type="file" id="files" name="files[]" multiple /><br />
  34.   ▼読込んだファイル(テキストファイル)を表示する<br />
  35.   <div style="border:1px solid #ccc;padding:0.5em;background:#f5f5f5;" id="list"></div>
  36. </div>
  37. <div style="font-size:10pt;text-align:right;margin-top:0.5em;">
  38. <a href="//tips.recatnap.info/" target="_top">PCスキルの小技・忘却防止メモ</a> -
  39. <a href="//tips.recatnap.info/wiki/" target="_top">PCスキルの小技・忘却防止メモのまとめ(wiki)</a>
  40. </div>
  41. <div style="font-size:10pt;text-align:center;margin-top:0.5em;padding:0.5em;border-top:1px solid #ccc;">
  42. Copyright &copy; 2009 by PCスキルの小技・忘却防止メモ. All rights reserved.
  43. </div>
  44. </body>
  45. </html>