2012-12-04 24 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

啊這是可能的FileReader,我已經做了這樣的一個例子,下面的代碼:

<!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

感謝帖子!然而,有一些我不明白的是:爲什麼'reader'或'this'不是'e.target'而是它們都引用FileReader對象:** [demo](http:// jsfiddle.net/Mori/tJBHZ/)**。 – Mori

+0

對於「this」這個關鍵字,實際上只是一個個人喜好的東西,除非它內聯在一個元素上,我並不打擾它太多... http://tech.pro/tutorial/1192/avoiding-the-this-problem -in-javascript 至於「讀者」,是的,這可能是一個有效的觀點,但是再次,不要用某種方式來「混淆」「讀取」。如果有多種方式可以引用某個對象,那麼我會說去找一個你最適合閱讀的對象。 – bcmoney

9

出於安全原因,Javascript無權訪問用戶的文件系統。 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>