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

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


当前回答

此函数适用于浏览器和打开文件选择对话框,在用户选择后将文件读取为二进制并调用读取数据的回调函数:

function pickAndReadFile(callback) {
    var el = document.createElement('input');
    el.setAttribute('type', 'file');
    el.style.display = 'none';
    document.body.appendChild(el);
    el.onchange = function (){
        const reader = new FileReader();
        reader.onload = function () {
            callback(reader.result);
            document.body.removeChild(el);
        };
        reader.readAsBinaryString(el.files[0]);
    }
    el.click();
}

像这样使用它:

pickAndReadFile(data => {
  console.log(data)
})

其他回答

这是一个老问题,但有两个主要观点我们必须弄清楚。我们是想读取整个文件还是逐行获取?

泰欧,我想要完整的文件然后再处理。

好的,这很简单,我们只需调用text(记住,text假设文件是UTF-8编码的),并像这样处理文件:

const $output = document.getElementById('output') const $file = document.getElementById('file') const fetchFile = async e => { Const [file] = e.target.files Const text = await file.text() 美元输出。textContent = text } 美元的文件。onchange = fetchFile <input id='file' type='file' accept='text/plain'><br> < pre id =“输出”>…< / >之前

那一行一行呢?这是可能的?

好吧,我的小徒弟,这也是可能的我们只需要像这样把文本分成几行

const $output = document.getElementById('output') const $file = document.getElementById('file') 让数 const fetchFile = async e => { Const [file] = e.target.files If (!file)返回 计数= 0 Const text = await file.text() 美元输出。textContent = text Const lines = text.split(/\r?\n/gm) For (const line of lines) { 如果(行)计数++ } console.log({数}) } 美元的文件。onchange = fetchFile <input id='file' type='file' accept='text/plain'><br> < pre id =“输出”>…< / >之前

这可能会有帮助,

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

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>

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

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

如果你想提示用户选择一个文件,那么读取它的内容:

// read the contents of a file input
const readInputFile = (inputElement, callback) => {
  const reader = new FileReader();
  reader.onload = () => {
    callback(reader.result)
  };
  reader.readAsText(inputElement.files[0]);
};
// create a file input and destroy it after reading it
const openFile = (callback) => {
  var el = document.createElement('input');
  el.setAttribute('type', 'file');
  el.style.display = 'none';
  document.body.appendChild(el);
  el.onchange = () => {readInputFile(el, (data) => {
    callback(data)
    document.body.removeChild(el);
  })}
  el.click();
}

用法:

// prompt the user to select a file and read it
openFile(data => {
    console.log(data)
  })