【问题标题】:How to read text file in JavaScript如何在 JavaScript 中读取文本文件
【发布时间】:2012-11-22 11:12:46
【问题描述】:

我正在尝试将文本文件加载到我的 JavaScript 文件中,然后从该文件中读取行以获取信息,我尝试了 FileReader,但它似乎不起作用。有人可以帮忙吗?

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

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

【问题讨论】:

标签: javascript html text


【解决方案1】:

是的,使用 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>

也可以使用 ActiveX 对象来支持一些旧版本的 IE(我认为是 6-8),我有一些旧代码也可以这样做,但是 已经有一段时间了,所以我我必须挖掘它我找到了一个类似于我使用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>

【讨论】:

  • 感谢您的帖子!但是,有一点我不明白:为什么不使用readerthis 而不是e.target,而它们都指的是FileReader 对象:demo
  • 对于“this”关键字,真的只是个人喜好,除非它内联在一个元素上,否则我不会太在意它...tech.pro/tutorial/1192/avoiding-the-this-problem-in-javascript至于“读者”,是的,这是一个它可能是有效的点,但同样,不喜欢以“阅读”令人困惑的方式使用项目。如果有多种方法可以引用一个对象,我会说选择你以后阅读时最舒服的那个。
【解决方案2】:

这可以很容易地使用 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" );

【讨论】:

  • 我不明白,在函数 FileHelpef 内部设置了 FileHelpef 本身的静态属性,然后立即调用该方法,但如果从未调用函数 FileHelper 本身,则静态属性从来没有设置过,不应该都在函数之外吗?
【解决方案3】:

出于安全原因,Javascript 无法访问用户的文件系统。 FileReader 仅适用于用户手动选择的文件。

【讨论】:

  • 这是假设 OP 正在讨论客户端计算机上的文件。如果它在服务器上可用,则可以通过 AJAX 加载。
【解决方案4】:

(小提琴: https://jsfiddle.net/ya3ya6/7hfkdnrg/2/)

  1. 用法

HTML:

<textarea id='tbMain' ></textarea>
<a id='btnOpen' href='#' >Open</a>

Js:

document.getElementById('btnOpen').onclick = function(){
    openFile(function(txt){
        document.getElementById('tbMain').value = txt; 
    });
}
  1. Js 助手函数
function openFile(callBack){
  var element = document.createElement('input');
  element.setAttribute('type', "file");
  element.setAttribute('id', "btnOpenFile");
  element.onchange = function(){
      readText(this,callBack);
      document.body.removeChild(this);
      }

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();
}

function readText(filePath,callBack) {
    var reader;
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        reader = new FileReader();
    } else {
        alert('The File APIs are not fully supported by your browser. Fallback required.');
        return false;
    }
    var output = ""; //placeholder for text output
    if(filePath.files && filePath.files[0]) {           
        reader.onload = function (e) {
            output = e.target.result;
            callBack(output);
        };//end onload()
        reader.readAsText(filePath.files[0]);
    }//end if html5 filelist support
    else { //this is where you could fallback to Java Applet, Flash or similar
        return false;
    }       
    return true;
}

【讨论】:

    【解决方案5】:

    我的例子

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

    【讨论】:

      猜你喜欢
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多