首页 文章

如何阅读本地文本文件?

提问于
浏览
258

我试图通过创建一个函数来编写一个简单的文本文件阅读器,该函数接收文件的路径并将每行文本转换为char数组,但它不起作用 .

function readTextFile() {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "testing.txt", true);
  rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4) {
      var allText = rawFile.responseText;
      document.getElementById("textSection").innerHTML = allText;
    }
  }
  rawFile.send();
}

这里出了什么问题?

previous revision稍微更改代码后,这似乎仍然无效,现在它给了我一个 XMLHttpRequest 异常101 .

我已经在Firefox上测试了它并且它可以工作,但是在谷歌Chrome中它不会工作并且它一直给我一个例外101.我如何才能让它不仅可以用于Firefox,还可以用于其他浏览器(尤其是Chrome) )?

10 回答

  • 12

    你需要检查状态0(当使用 XMLHttpRequest 本地加载文件时,你不要't get a status returned because it'来自 Webserver

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    

    并在您的文件名中指定 file://

    readTextFile("file:///C:/your/path/to/file.txt");
    
  • 239

    访问Javascripture!然后转到 readAsText 部分并尝试示例 . 您将能够知道 FileReaderreadAsText 功能如何工作 .

    <html>
        <head>
        <script>
          var openFile = function(event) {
            var input = event.target;
    
            var reader = new FileReader();
            reader.onload = function(){
              var text = reader.result;
              var node = document.getElementById('output');
              node.innerText = text;
              console.log(reader.result.substring(0, 200));
            };
            reader.readAsText(input.files[0]);
          };
        </script>
        </head>
        <body>
        <input type='file' accept='text/plain' onchange='openFile(event)'><br>
        <div id='output'>
        ...
        </div>
        </body>
        </html>
    
  • 6

    在javascript中引入fetch api之后,读取文件内容变得更加简单 .

    reading a text file

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    

    reading a json file

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    

    更新30/07/2018(免责声明):

    这种技术在Firefox中运行良好,但似乎Chrome的fetch实现在编写此更新之日不支持file:/// URL方案(在Chrome 68中测试) .

  • 69
    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    
    <input type="file" id="myFile">
    <hr>
    <textarea style="width:500px;height: 400px" id="output"></textarea>
    
  • 11

    尝试创建两个函数:

    function getData(){       //this will read file and send information to other function
           var xmlhttp;
    
           if (window.XMLHttpRequest) {
               xmlhttp = new XMLHttpRequest();               
           }           
           else {               
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");               
           }
    
           xmlhttp.onreadystatechange = function () {               
               if (xmlhttp.readyState == 4) {                   
                 var lines = xmlhttp.responseText;    //*here we get all lines from text file*
    
                 intoArray(lines);     *//here we call function with parameter "lines*"                   
               }               
           }
    
           xmlhttp.open("GET", "motsim1.txt", true);
           xmlhttp.send();    
    }
    
    function intoArray (lines) {
       // splitting all text data into array "\n" is splitting data from each new line
       //and saving each new line as each element*
    
       var lineArr = lines.split('\n'); 
    
       //just to check if it works output lineArr[index] as below
       document.write(lineArr[2]);         
       document.write(lineArr[3]);
    }
    
  • 11

    其他例子 - 我的读者使用FileReader类

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

    乔恩佩里曼,

    是js可以读取本地文件(请参阅FileReader()),但不能自动读取:用户必须使用html <input type=file> 将文件或文件列表传递给脚本 .

    然后使用js可以处理(示例视图)文件或文件列表,它们的一些属性以及文件或文件内容 .

    出于安全原因,js不能做的是自动访问(无需用户输入)到他的计算机的文件系统 .

    要允许js自动访问本地fs,需要创建一个内部没有js的html文件,而是创建一个hta文档 .

    一个hta文件里面可以包含js或vbs .

    但是hta可执行文件仅适用于Windows系统 .

    这是标准的浏览器行为 .

    google chrome也在fs api工作,更多信息来自:http://www.html5rocks.com/en/tutorials/file/filesystem/

  • 11

    很可能你已经尝试过,输入“false”如下:

    rawFile.open("GET", file, false);
    
  • 20

    这可能有所帮助,

    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                alert(xmlhttp.responseText);
            }
        }
    
        xmlhttp.open("GET", "sample.txt", true);
        xmlhttp.send();
    
  • 1
    <html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {            
                    $.ajax({`enter code here`
                        url: "TextFile.txt",
                        dataType: "text",
                        success: function (data) {                 
                                var text = $('#newCheckText').val();
                                var str = data;
                                var str_array = str.split('\n');
                                for (var i = 0; i < str_array.length; i++) {
                                    // Trim the excess whitespace.
                                    str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
                                    // Add additional code here, such as:
                                    alert(str_array[i]);
                                    $('#checkboxes').append('<input type="checkbox"  class="checkBoxClass" /> ' + str_array[i] + '
    '); } } }); $("#ckbCheckAll").click(function () { $(".checkBoxClass").prop('checked', $(this).prop('checked')); }); }); </script> </head> <body> <div id="checkboxes"> <input type="checkbox" id="ckbCheckAll" class="checkBoxClass"/> Select All
    </div> </body> </html>

相关问题