Javascript 如何读取本地文本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14446447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:47:39  来源:igfitidea点击:

How to read a local text file?

javascriptfile-ioxmlhttprequest

提问by Danny

I'm trying to write a simple text file reader by creating a function that takes in the file's path and converts each line of text into a char array, but it's not working.

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

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();
}

What is going wrong here?

这里出了什么问题?

This still doesn't seem to work after changing the code a little bit from a previous revisionand now it's giving me an XMLHttpRequestexception 101.

以前的修订版中稍微更改代码后,这似乎仍然不起作用,现在它给了我一个XMLHttpRequest异常 101。

I've tested this on Firefox and it works, but in Google Chrome it just won't work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers (especially Chrome)?

我已经在 Firefox 上测试了它并且它可以工作,但是在 Google Chrome 中它不起作用并且它一直给我一个异常 101。我怎样才能让它不仅在 Firefox 上工作,而且在其他浏览器上工作(尤其是 Chrome )?

采纳答案by Majid Laissi

You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver)

您需要检查状态 0(当使用 本地加载文件时XMLHttpRequest,您不会得到状态返回,因为它不是来自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);
}

And specify file://in your filename:

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

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

回答by Amit Chaurasia

Visit Javascripture! And go the section readAsTextand try the example. You will be able to know how the readAsTextfunction of FileReaderworks.

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

回答by Abdelaziz Mokhnache

After the introduction of fetch apiin javascript, reading file contents could not be simpler.

在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

读取一个json文件

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

Update 30/07/2018 (disclaimer):

2018 年 7 月 30 日更新(免责声明):

This technique works fine in Firefox, but it seems like Chrome's fetchimplementation does not support file:///URL scheme at the date of writing this update (tested in Chrome 68).

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

Update-2 (disclaimer):

更新 2(免责声明):

This technique does not work with Firefoxabove version 68 (Jul 9, 2019) for the same (security) reason as Chrome: CORS request not HTTP. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp.

这种技术不工作的Firefox以上68版(2019年7月9日),对于相同的(安全)的理由,铬:CORS request not HTTP。请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp

回答by Poornachander K

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>

回答by Sparrow

Jon Perryman,

乔恩·佩里曼

Yes js can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html <input type=file>.

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

Then with js it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.

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

What js cannot do for security reasons is to access automatically (without the user input) to the filesystem of his computer.

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

To allow js to acccess to the local fs automatically is needed to create not an html file with js inside it but an hta document.

为了让 js 自动访问本地 fs,需要创建的不是一个包含 js 的 html 文件,而是一个 hta 文档。

An hta file can contain js or vbs inside it.

hta 文件中可以包含 js 或 vbs。

But the hta executable will work on windows systems only.

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

This is standard browser behavior.

这是标准的浏览器行为。

Also google chrome worked at the fs api, more infos here: http://www.html5rocks.com/en/tutorials/file/filesystem/

谷歌浏览器也在 fs api 上工作,更多信息在这里:http: //www.html5rocks.com/en/tutorials/file/filesystem/

回答by momen

Provably you already try it, type "false" as follows:

证明你已经尝试过了,输入“false”如下:

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

回答by Motsim Mansoor

Try creating two functions:

尝试创建两个函数:

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]);
}

回答by websky

other example - my reader with FileReader class

其他示例 - 我的带有 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>

回答by barro32

Using Fetchand async function

使用Fetch和 async 函数

const logFileText = async file => {
    const response = await fetch(file)
    const text = await response.text()
    console.log(text)
}

logFileText('file.txt')

回答by Sameera R.

This might help,

这可能会有所帮助,

    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();