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

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)上工作?


当前回答

这可能会有帮助,

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

其他回答

为了通过JavaScript使用chrome读取本地文件文本,chrome浏览器应该运行参数——allow-file-access-from-files来允许JavaScript访问本地文件,然后你可以像下面这样使用XmlHttpRequest读取它:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
   if (xmlhttp.readyState == 4) {
       var allText = xmlhttp.responseText;          
            }
        };
xmlhttp.open("GET", file, false);
xmlhttp.send(null);

现代的解决方案:

使用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,以防止你想要对用户选择的文件进行永久的读取访问(甚至是写入访问)。

使用Fetch和async函数

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

logFileText('file.txt')

在javascript中引入fetch api之后,读取文件内容变得非常简单。

读取文本文件

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

读取json文件

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中测试)。

更新2(免责声明):

此技术不适用于版本68(2019年7月9日)以上的Firefox,原因与Chrome相同(安全):CORS请求而不是HTTP。见https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp。

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