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

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


当前回答

如何读取本地文件?

通过使用这个,你将通过loadText()加载一个文件,然后JS将异步等待,直到文件被读取和加载之后,它将执行readText()函数,允许你继续使用正常的JS逻辑(你也可以在loadText()函数上写一个try catch块,以防出现任何错误),但在这个例子中,我将它保持在最小。

async function loadText(url) {
    text = await fetch(url);
    //awaits for text.text() prop 
    //and then sends it to readText()
    readText(await text.text());
}

function readText(text){
    //here you can continue with your JS normal logic
    console.log(text);
}

loadText('test.txt');

其他回答

这可能会有帮助,

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

是的,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/

加上上面的一些答案,这个修改后的解决方案对我来说很有效。

<input id="file-upload-input" type="file" class="form-control" accept="*" />

....

let fileInput  = document.getElementById('file-upload-input');
let files = fileInput.files;

//Use createObjectURL, this should address any CORS issues.
let filePath = URL.createObjectURL(files[0]);

....

function readTextFile(filePath){
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", filePath , true);
    rawFile.send(null);

    rawFile.onreadystatechange = function (){
        if(rawFile.readyState === 4){
            if(rawFile.status === 200 || rawFile.status == 0){
                var allText = rawFile.responseText;
                console.log(allText);
            }
        }
    }     
}

由于同源策略的原因,Chrome不支持本地AJAX调用。

chrome上的错误信息是这样的: “跨源请求不支持协议方案:http, data, chrome, chrome-extension, https。”

这意味着chrome为每个域创建一个虚拟磁盘,以保存使用http/https协议的域提供的文件。对该虚拟磁盘以外的任何文件的访问都受到同源策略的限制。AJAX请求和响应发生在http/https上,因此不适用于本地文件。

Firefox没有这样的限制,因此您的代码可以在Firefox上愉快地工作。然而,铬也有变通办法:请看这里。

使用Fetch和async函数

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

logFileText('file.txt')