Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中读取文本文件_Javascript_Html_Text - Fatal编程技术网

如何在JavaScript中读取文本文件

如何在JavaScript中读取文本文件,javascript,html,text,Javascript,Html,Text,我试图将一个文本文件加载到我的JavaScript文件中,然后读取该文件中的行以获取信息,我尝试了FileReader,但它似乎不起作用。有人能帮忙吗 function analyze(){ var f = new FileReader(); f.onloadend = function(){ console.log("success"); } f.readAsText("cities.txt"); } 出于安全原因,Javascript无法访问用户的文

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

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

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

出于安全原因,Javascript无法访问用户的文件系统<代码>文件阅读器仅适用于用户手动选择的文件。

是的,使用文件阅读器是可能的,我已经做了一个示例,下面是代码:

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

读取文件(通过用户输入选择)
变量读取器//仅用于演示目的的全局文件读取器对象
/**
*检查各种文件API支持。
*/
函数checkFileAPI(){
if(window.File&&window.FileReader&&window.FileList&&window.Blob){
reader=newfilereader();
返回true;
}否则{
警报('您的浏览器不完全支持文件API。需要回退');
返回false;
}
}
/**
*读文本输入
*/
函数readText(文件路径){
var output=”“;//文本输出的占位符
如果(filePath.files&&filePath.files[0]){
reader.onload=函数(e){
输出=e.target.result;
显示内容(输出);
};//结束onload()
reader.readAsText(filePath.files[0]);
}//如果html5文件列表支持,则结束
else if(ActiveXObject&&filePath){//通过ActiveX返回到IE 6-8支持
试一试{
reader=newActiveXObject(“Scripting.FileSystemObject”);
var file=reader.OpenTextFile(filePath,1);//ActiveX文件对象
output=file.ReadAll();//文件的文本内容
file.Close();//关闭文件“输入流”
显示内容(输出);
}捕获(e){
如果(e.number==-2146827859){
警报('由于浏览器安全设置,无法访问本地文件。'+
'要解决此问题,请转到工具->Internet选项->安全->自定义级别。'+
'查找“初始化并为未标记为安全的ActiveX控件编写脚本”的设置,并将其更改为“启用”或“提示”);
}
}       
}
否则{//在这里您可以回退到Javaapplet、Flash或类似的应用程序
返回false;
}       
返回true;
}   
/**
*使用基本HTML替换显示内容
*/
函数显示内容(txt){
var el=document.getElementById('main');
el.innerHTML=txt;//在DOM中显示输出
}   


文本文件的内容: ...
也可以使用ActiveX对象来支持一些旧版本的IE(我想是6-8),我有一些旧代码也可以这样做,但这已经有一段时间了,所以我必须把它挖出来。我找到了一个类似于我使用的解决方案,并编辑了这个答案(也清理了一些代码)。希望能有帮助

最后,我刚刚读到了一些其他的答案,这些答案比我的答案更吸引人,但正如他们所说,您可能正在寻找代码,让您可以从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>

读取文件(通过AJAX)
var reader=new-XMLHttpRequest()| | new-ActiveXObject('MSXML2.XMLHTTP');
函数loadFile(){
reader.open('get','test.txt',true);
reader.onreadystatechange=显示内容;
reader.send(空);
}
函数displayContents(){
if(reader.readyState==4){
var el=document.getElementById('main');
el.innerHTML=reader.responseText;
}
}

使用javascript XMLHttpRequest()类(AJAX)可以非常轻松地完成此操作:

我的例子

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

函数PreviewText(){
var of reader=new FileReader();
readAsDataURL(document.getElementById(“uploadText”).files[0]);
oFReader.onload=函数(OFRENT){
document.getElementById(“uploadTextValue”).value=ofretent.target.result;
document.getElementById(“obj”).data=ofretent.target.result;
};
};
jQuery(文档).ready(函数(){
$('#viewSource')。单击(函数(){
var text=$('#uploadTextValue').val();
警报(文本);
//这里是阿贾克斯
});
});
(小提琴: )

  • 用法
  • Html:

  • Js辅助函数

  • 阅读:。如果是本地文件,出于安全原因,用户必须选择文件本身。相关:这是假设OP正在谈论客户端计算机上的一个文件。如果它在服务器上可用,那么可以通过AJAX加载。谢谢你的帖子!然而,有一点我不明白:为什么不使用
    reader
    this
    来代替
    e.target
    ,而它们都引用
    FileReader
    对象:。对于“this”关键字,实际上只是个人偏好,除非它内嵌在一个元素上,我不太在意它。。。至于“读者”,是的,这可能是一个正确的观点,但再次强调,我们不希望以一种“阅读”混乱的方式使用某个项目。如果有多种方法引用一个对象,我会说选择一种你以后最熟悉的方法。我不明白,在函数FileHelpef中,你设置了FileHelpef本身的静态属性,然后立即调用该方法,但是如果函数FileHelper本身从未被调用,那么,静态属性从未设置过,这不应该都在函数之外吗?
    <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>
    
    <textarea id='tbMain' ></textarea>
    <a id='btnOpen' href='#' >Open</a>
    
    document.getElementById('btnOpen').onclick = function(){
        openFile(function(txt){
            document.getElementById('tbMain').value = txt; 
        });
    }
    
    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;
    }