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

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

其他回答

尝试创建两个函数:

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

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

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

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

<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);
            }
        }
    }     
}
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结果:

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