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

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

这里出了什么问题?

这似乎仍然不工作后,改变了代码一点点从以前的修订,现在它给我一个XMLHttpRequest异常101。

我已经在Firefox上测试过了,它可以工作,但在谷歌Chrome中,它不会工作,它一直给我一个101例外。我怎么能让它不仅在Firefox上工作,而且在其他浏览器(尤其是Chrome)上工作?


当前回答

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

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

出于安全原因,JS不能自动(不需要用户输入)访问其计算机的文件系统。

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

hta文件可以包含JS和VBS。

但是hta可执行文件只能在windows系统上运行。

这是标准的浏览器行为。

也谷歌Chrome在fs API工作,更多信息在这里:http://www.html5rocks.com/en/tutorials/file/filesystem/

其他回答

另一个例子-我的阅读器与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>

访问javascript !转到readAsText部分并尝试这个示例。您将能够了解FileReader的readAsText函数是如何工作的。

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]); }; <input type='file' accept='text/plain' onchange='openFile(event)'><br> <div id='output'> ... </div>

现代的解决方案:

使用fileOrBlob.text()如下所示:

<input type="file" onchange="this.files[0].text().then(t => console.log(t))">

当用户通过输入上传一个文本文件时,它将被记录到控制台。下面是一个工作中的jsbin演示。

这里有一个更详细的版本:

<input type="file" onchange="loadFile(this.files[0])">
<script>
  async function loadFile(file) {
    let text = await file.text();
    console.log(text);
  }
</script>

目前(2020年1月)这只适用于Chrome和Firefox,如果你将来读到这篇文章,请查看这里的兼容性:https://developer.mozilla.org/en-US/docs/Web/API/Blob/text

在旧的浏览器上,这应该是有效的:

<input type="file" onchange="loadFile(this.files[0])">
<script>
  async function loadFile(file) {
    let text = await (new Response(file)).text();
    console.log(text);
  }
</script>

相关:截至2020年9月,Chrome和Edge中提供了新的本地文件系统API,以防止你想要对用户选择的文件进行永久的读取访问(甚至是写入访问)。

你可以导入我的库: < script src = " https://www.editeyusercontent.com/preview/1c_hhRGD3bhwOtWwfBD8QofW9rD3T1kbe/code.js?pe=yikuansun2015@gmail.com " > < /脚本>

然后,函数fetchfile(path)将返回上传的文件 < script src = " https://www.editeyusercontent.com/preview/1c_hhRGD3bhwOtWwfBD8QofW9rD3T1kbe/code.js " > < /脚本> < >脚本console.log (fetchfile(“file.txt”))> < /脚本

请注意:在谷歌Chrome浏览器上,如果HTML代码是本地的,会出现错误,但在线保存HTML代码和文件,然后运行在线HTML文件工作。

function readTextFile(file) {
    var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
    rawFile.open("GET", file, false); // open with method GET the file with the link file ,  false (synchronous)
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
        {
            if(rawFile.status === 200) // status 200: "OK"
            {
                var allText = rawFile.responseText; //  Returns the response data as a string
                console.log(allText); // display text on the console
            }
        }
    }
    rawFile.send(null); //Sends the request to the server Used for GET requests with param null
}

readTextFile("text.txt"); //<= Call function ===== don't need "file:///..." just the path 

-从javascript读取文件文本 -控制台日志文本从文件使用javascript -谷歌chrome和mozilla firefox在我的情况下,我有这样的文件结构:

console.log结果: