如何阅读JavaScript中的文本文件 [英] How to read text file in JavaScript

查看:93
本文介绍了如何阅读JavaScript中的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文本文件加载到我的JavaScript文件中,然后从该文件中读取行以获取信息,我尝试了FileReader但它似乎没有工作。任何人都可以帮忙吗?

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

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


解决方案

是的,FileReader ,我已经做了一个这样的例子,下面是代码:

 <!DOCTYPE html> 
< html>
< head>
< title>读取文件(通过用户输入选择)< / title>
< script type =text / javascript>
var阅读器; // GLOBAL File Reader对象仅用于演示目的
$ b $ / **
*检查各种File API支持。 ($ window.File& window.FileReader&& window.FileList&& window.Blob){
reader = new FileReader();
返回true;
} else {
alert('您的浏览器不支持File API,需要后备。');
返回false;


$ b $ ** b $ b *读取文本输入
* /
函数readText(filePath){
var output =; (文件路径.files&& filePath.files [0]){
reader.onload = function(e){
output = e.target。结果;
displayContents(output);
}; // end onload()
reader.readAsText(filePath.files [0]);
} // end if html5 filelist支持
else if(ActiveXObject&& filePath){//通过ActiveX回退到IE 6-8支持
try {
reader =新的ActiveXObject(Scripting.FileSystemObject);
var file = reader.OpenTextFile(filePath,1); // ActiveX文件对象
output = file.ReadAll(); //文件的文本内容
file.Close(); //关闭文件输入流
displayContents(output);
catch(e){
if(e.number == -2146827859){
alert('由于浏览器安全设置而无法访问本地文件。'+
'要解决这个问题,请转至工具 - > Internet选项 - >安全性>自定义级别。'+
'找到未标记为安全的初始化和脚本ActiveX控件设置并将其更改为启用或提示);
}
}
}
else {//这是你可以回退到Java Applet,Flash或类似的
返回false;
}
返回true;
}

/ **
*使用基本HTML替换显示内容
* /
函数displayContents(txt){
var el = document.getElementById('main');
el.innerHTML = txt; //在DOM
中显示输出}
< / script>
< / head>
< body onload =checkFileAPI();>
< div id =container>
< input type =fileonchange ='readText(this)'/>
< br />
< hr />
< h3>文本文件的内容:< / h3>
< div id =main>
...
< / div>
< / div>
< / body>
< / html>

也可以做同样的事情来支持一些旧版本的IE(我认为6-8 )使用ActiveX对象,我有一些旧的代码也可以做到这一点,但是已经有一段时间了,所以我不得不把它挖出来我找到了一个类似于我使用的解决方案的解决方案 Jacky Cui的博客并编辑这个答案(也清理了一下代码)。希望它有帮助。

最后,我刚刚阅读了一些其他的答案,这些答案打败了我,但正如他们所建议的那样,您可能正在寻找可以让您加载来自JavaScript文件所在的服务器(或设备)的文本文件。如果是这种情况,那么您希望AJAX代码动态加载文档,如下所示:

 <!DOCTYPE html> ; 
< html>
< head>< meta charset =utf-8/>
< title>读取文件(通过AJAX)< / title>
< script type =text / javascript>
var reader = new XMLHttpRequest()||新的ActiveXObject('MSXML2.XMLHTTP');

函数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 =buttonvalue =test.txtonclick =loadFile()/>
< div id =main>
< / div>
< / div>
< / body>
< / html>


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

<!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). 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. If that's the case then you want AJAX code to load the document dynamically which would be something as follows:

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

这篇关于如何阅读JavaScript中的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆