如何在JavaScript中读取文本文件

83qze16e  于 2023-04-19  发布在  Java
关注(0)|答案(7)|浏览(146)

我试图将一个文本文件加载到我的JavaScript文件中,然后读取该文件中的行以获取信息,我尝试了FileReader,但它似乎不起作用。有人可以帮助吗?

function analyze(){
   var f = new FileReader();

   f.onloadend = function(){
       console.log("success");
   }
   f.readAsText("cities.txt");
}
js81xvg6

js81xvg61#

是的,这是可能的FileReader,我已经做了一个例子,这是代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Read File (via User Input selection)</title>
    <script type="text/javascript">
    var reader; //GLOBAL File Reader object for demo purpose only

    /**
     * Check for the various File API support.
     */
    function checkFileAPI() {
        if (window.File && window.FileReader && window.FileList && window.Blob) {
            reader = new FileReader();
            return true; 
        } else {
            alert('The File APIs are not fully supported by your browser. Fallback required.');
            return false;
        }
    }

    /**
     * read text input
     */
    function readText(filePath) {
        var output = ""; //placeholder for text output
        if(filePath.files && filePath.files[0]) {           
            reader.onload = function (e) {
                output = e.target.result;
                displayContents(output);
            };//end onload()
            reader.readAsText(filePath.files[0]);
        }//end if html5 filelist support
        else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
            try {
                reader = new ActiveXObject("Scripting.FileSystemObject");
                var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
                output = file.ReadAll(); //text contents of file
                file.Close(); //close file "input stream"
                displayContents(output);
            } catch (e) {
                if (e.number == -2146827859) {
                    alert('Unable to access local files due to browser security settings. ' + 
                     'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' + 
                     'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"'); 
                }
            }       
        }
        else { //this is where you could fallback to Java Applet, Flash or similar
            return false;
        }       
        return true;
    }   

    /**
     * display content using a basic HTML replacement
     */
    function displayContents(txt) {
        var el = document.getElementById('main'); 
        el.innerHTML = txt; //display output in DOM
    }   
</script>
</head>
<body onload="checkFileAPI();">
    <div id="container">    
        <input type="file" onchange='readText(this)' />
        <br/>
        <hr/>   
        <h3>Contents of the Text file:</h3>
        <div id="main">
            ...
        </div>
    </div>
</body>
</html>

它也可以做同样的事情,以支持一些旧版本的IE(我认为6-8)使用ActiveX对象,我有一些旧的代码,这也做了,但它已经有一段时间了,所以我必须挖掘它,我已经找到了一个解决方案类似于我使用的礼貌Jacky Cui's blog和编辑这个答案(也清理代码一点)。希望它有帮助。
最后,我刚刚读了一些其他的答案,但正如他们所建议的,你可能正在寻找代码,让你从JavaScript文件所在的服务器(或设备)加载文本文件。如果是这种情况,那么你希望 AJAX 代码动态加载文档,这将是如下所示:

<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>Read File (via AJAX)</title>
<script type="text/javascript">
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');

function loadFile() {
    reader.open('get', 'test.txt', true); 
    reader.onreadystatechange = displayContents;
    reader.send(null);
}

function displayContents() {
    if(reader.readyState==4) {
        var el = document.getElementById('main');
        el.innerHTML = reader.responseText;
    }
}

</script>
</head>
<body>
<div id="container">
    <input type="button" value="test.txt"  onclick="loadFile()" />
    <div id="main">
    </div>
</div>
</body>
</html>
wtzytmuj

wtzytmuj2#

这可以很容易地使用javascript XMLHttpRequest()类( AJAX )完成:

function FileHelper()

{
    FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
    {
        var request = new XMLHttpRequest();
        request.open("GET", pathOfFileToReadFrom, false);
        request.send(null);
        var returnValue = request.responseText;

        return returnValue;
    }
}

...

var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
mzsu5hc0

mzsu5hc03#

出于安全原因,Javascript无法访问用户的文件系统。FileReader仅用于用户手动选择的文件。

rqqzpn5f

rqqzpn5f4#

(fiddle:https://jsfiddle.net/ya3ya6/7hfkdnrg/2/
1.用途
Html:

<textarea id='tbMain' ></textarea>
<a id='btnOpen' href='#' >Open</a>

Js:

document.getElementById('btnOpen').onclick = function(){
    openFile(function(txt){
        document.getElementById('tbMain').value = txt; 
    });
}
  1. Js Helper函数
function openFile(callBack){
  var element = document.createElement('input');
  element.setAttribute('type', "file");
  element.setAttribute('id', "btnOpenFile");
  element.onchange = function(){
      readText(this,callBack);
      document.body.removeChild(this);
      }

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();
}

function readText(filePath,callBack) {
    var reader;
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        reader = new FileReader();
    } else {
        alert('The File APIs are not fully supported by your browser. Fallback required.');
        return false;
    }
    var output = ""; //placeholder for text output
    if(filePath.files && filePath.files[0]) {           
        reader.onload = function (e) {
            output = e.target.result;
            callBack(output);
        };//end onload()
        reader.readAsText(filePath.files[0]);
    }//end if html5 filelist support
    else { //this is where you could fallback to Java Applet, Flash or similar
        return false;
    }       
    return true;
}
x0fgdtte

x0fgdtte5#

我的榜样

<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>
cbeh67ev

cbeh67ev6#

这是一个老问题,但我认为在2022年,ES6可以解决这个问题:

const $node = document.getElementById('output')
const $file = document.getElementById('file')

const processTextByLine = text => {
    const arr = text.split(/\r?\n/gm)
    arr.map(line => console.log(line))
}

const openFile = event => {
  const input = event.target
  if (!input) throw new Error('null input')
  const [first] = input.files

  const reader = new FileReader()
  reader.onload = () => {
    const text = reader.result
    $node.innerText = text
    
    processTextByLine(text)
  }
  
  reader.readAsText(first)
}

$file.onchange = openFile
<input id='file' type='file' accept='text/plain'><br>
<div id='output'>
  ...
</div>

如果您的文件是使用UTF-8编码的,那么我们可以使用Blob.text()进行async调用

const $node = document.getElementById('output')
const $file = document.getElementById('file')

const processTextByLine = text => {
    const arr = text.split(/\r?\n/gm)
    arr.map(line => console.log(line))
}

const openFile = async event => {
  const input = event.target
  if (!input) throw new Error('null input')
  const [file] = input.files
  const text = await file.text()
  $node.innerText = text
  processTextByLine(text)
}

$file.onchange = openFile
<input id='file' type='file' accept='text/plain'><br>
<div id='output'>
  ...
</div>

注意:

processTextByLine()函数是不需要的,它只是显示了一个情况下,如果我们需要处理的文件逐行。

t5fffqht

t5fffqht7#

这是我发现的最简单的方法。

HTML

<input type="file" id="upload">

JS

const inputElement = document.getElementById('upload')

inputElement.addEventListener('change', (e) => {
  if (!inputElement.files?.[0]) return

  const reader = new FileReader()
  reader.onload = (e) => {
    console.log(e.target.result)
  }
  reader.readAsText(inputElement.files[0])
})

相关问题