繁体   English   中英

如何读取 txt 文件并将其保存在 html 中 javascript 中的数组中

[英]How to read txt file and save it in array in javascript in html

对此有很多解决方案,但我在 html 网页上的 javascript 中发现很少或没有。 我有一个名为 sample.txt 的数据文件,位于我的 html 文件所在的位置。 我的目标是将 txt 文件加载到可用于创建表格并显示在 html 文件上的数组中。 我的 sample.text 文件有以下数据:

 sin 0.2 time 0.22222
 cos 0.3 time 0.43434
 tan 0.1 time 0.22221

我是 Javascript 的新手,我承认它比其他编程语言更难。 我熟悉 node.js 模式下的 javascript 但不熟悉 html 模式下的 javascript。 我设法创建了 html web 页面(如下所示)并在脚本模式下显示文本和数字等基础知识。 我还设法在脚本模式下按下按钮后加载 txt 文件并显示它。 这个 txt 加载方法是唯一对我有用的方法。 require (js) 方法既不工作也不导入。 如何从这种工作模式创建数据数组?

以下是我的完整代码(已更正),

  <!DOCTYPE html>
  <html>
  <head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <meta content="utf-8" http-equiv="encoding">
  <title>Read Text File</title> 
  </head> 

  <body> 
  <input type="file" name="inputfile"
        id="inputfile"> 
  <br> 

  <pre id="output"></pre> 
  <script>

  var file = document.getElementById('inputfile');

  file.addEventListener('change', () => {
  var txtArr = [];
  var fr = new FileReader();
  fr.onload = function() {
    // By lines
    var lines = this.result.split('\n');
    for (var line = 0; line < lines.length; line++) {
        txtArr = [...txtArr, ...(lines[line].split(" "))];
    }
   }
  fr.onloadend = function() {
    console.log(txtArr);
    document.getElementById('output').textContent=txtArr.join("");
    document.getElementById("output").innerHTML = txtArr[1]; 
    console.log(txtArr[1]);
  }

  fr.readAsText(file.files[0]);


  })

  </script>
  </body>
  </html> 

使用FileReader逐行获取字符串,然后将其拆分并合并到 resultArr 中,如下所示:

 var file = document.getElementById('inputfile'); file.addEventListener('change', () => { var txtArr = []; var fr = new FileReader(); fr.onload = function() { // By lines var lines = this.result.split('\n'); for (var line = 0; line < lines.length; line++) { txtArr = [...txtArr, ...(lines[line].split(" "))]; } } fr.onloadend = function() { console.log(txtArr); document.getElementById('output').textContent=txtArr.join(""); } fr.readAsText(file.files[0]); })
 <!DOCTYPE html> <html> <head> <title>Read Text File</title> </head> <body> <input type="file" name="inputfile" id="inputfile"> <br> <pre id="output"></pre> </body> </html>

其他方法不起作用的原因是因为 Javascript 无权访问文件系统。 为此,您需要一种服务器端语言,例如 NodeJS。

无论如何,这里有一些纯 Javascript 代码,可让您加载文本文件,将结果拆分为每行的文本数组,然后再次拆分这些数据以获得每行数据的数据 arrays。 作为一个小奖励,我还添加了一种方法来再次下载文本文件中的所有内容:

function loadFile(input, onloadCallback){
    const fr = new FileReader();

    fr.onload = onloadCallback;

    fr.readAsText(input);
}

/* Save file and force download */
function saveFile(data, fileName){
    const blob = new Blob([data], {type: 'text/csv'});
    if(window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveBlob(blob, fileName);
    } else {
        var elem = window.document.createElement('a');
        elem.href = window.URL.createObjectURL(blob);
        elem.download = fileName;        
        document.body.appendChild(elem);
        elem.click();
        document.body.removeChild(elem);
    }
}

/* Working with text files */
function openFile(ev){
    loadFile(ev.target.files[0], function(e) {
        // Get all the text as a string
        const result = e.target.result;

        // Make array out of result for each line
        const textArray = result.split("\r\n");

        // How to add new lines to the array if you want
        textArray.push("tan 0.2 time 0.23641");

        // Create dataArray for each line
        let dataArray = [];

        for(let i = 0; i < textArray.length; i++){
            const data = textArray[i].split(" ");

            dataArray.push(data);
        }

        // dataArray now contains arrays for each line of data
        console.log(dataArray);

        // Here's how you'd put a normal array back into a string
        const newString = textArray.join("\r\n");

        // Finally a way to download a file with the new string inside it
        saveFile(newString, 'test.txt');
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM