简体   繁体   English

如何在 JavaScript 中读取文本文件

[英]How to read text file in JavaScript

I am trying to load a text file into my JavaScript file and then read the lines from that file in order to get information, and I tried the FileReader but it does not seem to be working.我试图将一个文本文件加载到我的 JavaScript 文件中,然后从该文件中读取行以获取信息,我尝试了 FileReader,但它似乎不起作用。 Can anyone help?任何人都可以帮忙吗?

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

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

Yeah it is possible with FileReader, I have already done an example of this, here's the code:是的,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>

It's also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but its been a while so I'll have to dig it up I've found a solution similar to the one I used courtesy of Jacky Cui's blog and edited this answer (also cleaned up code a bit).也可以使用 ActiveX 对象做同样的事情来支持一些旧版本的 IE(我认为 6-8),我有一些旧代码也可以做到这一点,但已经有一段时间了,所以我必须把它挖出来我找到了一个类似于我在Jacky Cui 的博客上使用的解决方案并编辑了这个答案(也稍微清理了代码)。 Hope it helps.希望能帮助到你。

Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting.最后,我只是阅读了一些其他答案,这些答案让我大吃一惊,但正如他们所建议的那样,您可能正在寻找可以让您从 JavaScript 文件所在的服务器(或设备)加载文本文件的代码。 If that's the case then you want AJAX code to load the document dynamically which would be something as follows:如果是这种情况,那么您希望 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>

This can be done quite easily using javascript XMLHttpRequest() class (AJAX):这可以使用 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" );

Javascript doesn't have access to the user's filesystem for security reasons.出于安全原因,Javascript 无权访问用户的文件系统。 FileReader is only for files manually selected by the user. FileReader仅适用于用户手动选择的文件。

my example我的例子

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

(fiddle: https://jsfiddle.net/ya3ya6/7hfkdnrg/2/ ) (小提琴: https : //jsfiddle.net/ya3ya6/7hfkdnrg/2/

  1. Usage用法

Html:网址:

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

Js: JS:

document.getElementById('btnOpen').onclick = function(){
    openFile(function(txt){
        document.getElementById('tbMain').value = txt; 
    });
}
  1. Js Helper functions Js 辅助函数
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;
}

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

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