2012-12-04 10 views
31

JavaScriptファイルにテキストファイルを読み込み、情報を取得するためにそのファイルから行を読み込もうとして、FileReaderを試しましたが、動作していないようです。誰も助けることができますか?JavaScriptでテキストファイルを読む方法

function analyze(){ 
    var f = new FileReader(); 

    f.onloadend = function(){ 
     console.log("success"); 
    } 
    f.readAsText("cities.txt"); 
} 
+3

読む:http://www.html5rocks.com/en/tutorials/file/dndfiles/。ローカルファイルの場合、セキュリティ上の理由からファイル自体を選択する必要があります。関連:http://stackoverflow.com/questions/13428532/using-a-local-file-as-a-data-source-in-javascript – NullUserException

答えて

41

は、ここでのコードは次のとおりです。

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Read File (via User Input selection)</title> 
    <script type="text/javascript"> 
    var reader; //GLOBAL File Reader object for demo purpose only 

    /** 
    * Check for the various File API support. 
    */ 
    function checkFileAPI() { 
     if (window.File && window.FileReader && window.FileList && window.Blob) { 
      reader = new FileReader(); 
      return true; 
     } else { 
      alert('The File APIs are not fully supported by your browser. Fallback required.'); 
      return false; 
     } 
    } 

    /** 
    * read text input 
    */ 
    function readText(filePath) { 
     var output = ""; //placeholder for text output 
     if(filePath.files && filePath.files[0]) {   
      reader.onload = function (e) { 
       output = e.target.result; 
       displayContents(output); 
      };//end onload() 
      reader.readAsText(filePath.files[0]); 
     }//end if html5 filelist support 
     else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX 
      try { 
       reader = new ActiveXObject("Scripting.FileSystemObject"); 
       var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object 
       output = file.ReadAll(); //text contents of file 
       file.Close(); //close file "input stream" 
       displayContents(output); 
      } catch (e) { 
       if (e.number == -2146827859) { 
        alert('Unable to access local files due to browser security settings. ' + 
        'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' + 
        'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"'); 
       } 
      }  
     } 
     else { //this is where you could fallback to Java Applet, Flash or similar 
      return false; 
     }  
     return true; 
    } 

    /** 
    * display content using a basic HTML replacement 
    */ 
    function displayContents(txt) { 
     var el = document.getElementById('main'); 
     el.innerHTML = txt; //display output in DOM 
    } 
</script> 
</head> 
<body onload="checkFileAPI();"> 
    <div id="container">  
     <input type="file" onchange='readText(this)' /> 
     <br/> 
     <hr/> 
     <h3>Contents of the Text file:</h3> 
     <div id="main"> 
      ... 
     </div> 
    </div> 
</body> 
</html> 

それはIEの一部の古いバージョンをサポートするために同じことを行うことも可能です(私が思う6 -8)ActiveXオブジェクトを使用して、私はあまりにも古いコードを持っていましたが、はしばらくありましたので、私はJacky Cui's blogの礼儀と同じような解決策を見つけましたこの答え(また、コードを少しきれいにした)。それが役に立てば幸い。

最後に、私はドローに私を打ち負かすいくつかの答えを読んだだけですが、彼らが示唆するように、JavaScriptファイルが座っているサーバー(またはデバイス)からテキストファイルをロードできるコードを探しているかもしれません。その場合は、あなたは、次のようなものになるだろうどの動的に文書をロードするためのAJAXコードをしたい:

<!DOCTYPE html> 
<html> 
<head><meta charset="utf-8" /> 
<title>Read File (via AJAX)</title> 
<script type="text/javascript"> 
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP'); 

function loadFile() { 
    reader.open('get', 'test.txt', true); 
    reader.onreadystatechange = displayContents; 
    reader.send(null); 
} 

function displayContents() { 
    if(reader.readyState==4) { 
     var el = document.getElementById('main'); 
     el.innerHTML = reader.responseText; 
    } 
} 

</script> 
</head> 
<body> 
<div id="container"> 
    <input type="button" value="test.txt" onclick="loadFile()" /> 
    <div id="main"> 
    </div> 
</div> 
</body> 
</html> 
+0

投稿ありがとう!しかし、理解できないことがあります。なぜなら、それらがすべて 'FileReader'オブジェクトを参照している間に' e.target'の代わりに 'reader'や' this'が使われていないからです。** [demo](http:// jsfiddle.net/Mori/tJBHZ/)**。 – Mori

+0

"this"キーワードのために、本当に個人的な好みのものですが、その要素のインラインではあまり気にしません... http://tech.pro/tutorial/1192/avoiding-the-this-problem -in-javascript 「読者」に関しては、それは有効な点ですが、やはり混乱して「読み込む」方法で項目を使用しないことをお勧めします。オブジェクトを参照する方法が複数ある場合は、後ほど読むのが最も快適なものに行くといいでしょう。 – bcmoney

9

セキュリティ上の理由から、Javascriptはユーザーのファイルシステムにアクセスできません。 FileReaderは、ユーザーが手動で選択したファイルのみです。うん、それはFileReaderので可能である、私はすでにこの例を行っている

+2

これは、OPがクライアントコンピュータ上のファイルについて話していることを前提としています。サーバ上で利用できるものなら、AJAX経由でロードすることができます。 –

10

これではJavaScriptのXMLHttpRequest()クラス(AJAX)を使用して、非常に簡単に行うことができます。

function FileHelper() 

{ 
    FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom) 
    { 
     var request = new XMLHttpRequest(); 
     request.open("GET", pathOfFileToReadFrom, false); 
     request.send(null); 
     var returnValue = request.responseText; 

     return returnValue; 
    } 
} 

... 

var text = FileHelper.readStringFromFileAtPath ("mytext.txt"); 
+1

は私のためには機能しませんでした – Daniel

2

私の例

<html> 
    <head> 
     <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css"> 
     <script src="http://code.jquery.com/jquery-1.10.2.js"></script> 
     <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script> 
    </head> 
    <body> 
     <script> 
      function PreviewText() { 
      var oFReader = new FileReader(); 
      oFReader.readAsDataURL(document.getElementById("uploadText").files[0]); 
      oFReader.onload = function (oFREvent) { 
       document.getElementById("uploadTextValue").value = oFREvent.target.result; 
       document.getElementById("obj").data = oFREvent.target.result; 
      }; 
     }; 
     jQuery(document).ready(function(){ 
      $('#viewSource').click(function() 
      { 
       var text = $('#uploadTextValue').val(); 
       alert(text); 
       //here ajax 
      }); 
     }); 
     </script> 
     <object width="100%" height="400" data="" id="obj"></object> 
     <div> 
      <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" /> 
      <input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" /> 
     </div> 
     <a href="#" id="viewSource">Source file</a> 
    </body> 
</html> 
関連する問題