使用Javascript读取文本文件

时间:2015-05-26 08:30:36

标签: javascript html html5 text-files

以下代码应该在加载时读取当前目录中的文本文件的内容,并将其显示在html页面上。我尝试自己修改。但它没有给出输出。有没有更简单的方法来使用另一种方法获得此结果?或者请帮助弄清楚这段代码有什么问题?

<html>
        <head>
            <meta http-equiv='Content-type' content='text/html;charset=UTF-8' >
            <script>
    function startRead()
    {
      // obtain input element through DOM 

    var file = document.getElementById("\\file.txt").files[0]

      if(file)
        {
        getAsText(file);
      }
    }

    function getAsText(readFile)
    {
        var reader;
        try
        {
        reader = new FileReader();
        }catch(e)
        {
            document.getElementById('output').innerHTML = 
                "Error: seems File API is not supported on your browser";
          return;
      }

      // Read file into memory as UTF-8      
      reader.readAsText(readFile, "UTF-8");

      // Handle progress, success, and errors

      reader.onload = loaded;
      reader.onerror = errorHandler;
    }



    function loaded(evt)
    {
      // Obtain the read file data    
      var fileString = evt.target.result;
      document.getElementById('output').innerHTML = fileString;
    }

    function errorHandler(evt)
    {
      if(evt.target.error.code == evt.target.error.NOT_READABLE_ERR)
        {
        // The file could not be read
            document.getElementById('output').innerHTML = "Error reading file..."
      }
    }
    //Start reading file on load
    window.addEventListener("load", startRead() { }, false);

            </script>
        </head>

        <body>

            <pre>
                <code id="output">
                </code>
            </pre>
        </body>
    </html>

以下是我为了获得上述代码而修改的代码。我的意图是。当我打开html文件时,它将读取当前目录中的文本文件并显示内容。

<html>
    <head>
        <meta http-equiv='Content-type' content='text/html;charset=UTF-8' >
        <script>
function startRead()
{
  // obtain input element through DOM 

var file = document.getElementById("file").files[0];

  if(file)
    {
    getAsText(file);
  }
}

function getAsText(readFile)
{
    var reader;
    try
    {
    reader = new FileReader();
    }catch(e)
    {
        document.getElementById('output').innerHTML = 
            "Error: seems File API is not supported on your browser";
      return;
  }

  // Read file into memory as UTF-8      
  reader.readAsText(readFile, "UTF-8");

  // Handle progress, success, and errors

  reader.onload = loaded;
  reader.onerror = errorHandler;
}



function loaded(evt)
{
  // Obtain the read file data    
  var fileString = evt.target.result;
  document.getElementById('output').innerHTML = fileString;
}

function errorHandler(evt)
{
  if(evt.target.error.code == evt.target.error.NOT_READABLE_ERR)
    {
    // The file could not be read
        document.getElementById('output').innerHTML = "Error reading file..."
  }
}
        </script>
    </head>

    <body>
        <input id="file" type="file" multiple onchange="startRead()">
        <pre>
            <code id="output">
            </code>
        </pre>
    </body>
</html>

3 个答案:

答案 0 :(得分:4)

试试这个片段,我刚刚尝试过它可以运行:)!

Live Demo (With Input File)

&#13;
&#13;
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');

fileInput.addEventListener('change', function(e) {
    var file = fileInput.files[0];
    var textType = /text.*/;
    
    if (file.type.match(textType)) {
        var reader = new FileReader();
        
        reader.onload = function(e) {
            var content = reader.result;
            //Here the content has been read successfuly
            alert(content);
        }
        
        reader.readAsText(file);	
    } else {
        fileDisplayArea.innerText = "File not supported!"
    }
});
&#13;
<input type="file" id="fileInput">
&#13;
&#13;
&#13;

没有输入文件

<强>功能

function readTextFile(file){
            var rawFile = new XMLHttpRequest();
            rawFile.open("GET", file, false);
            rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
                {
                    if(rawFile.status === 200 || rawFile.status == 0)
                    {
                        var allText = rawFile.responseText;
                        alert(allText);
                    }
                }
            }
            rawFile.send(null);
        }

并测试它

<a href="#" onclick="readTextFile(&quot;file:///C:/test.txt&quot;)"> Test </a>

注意:我试过了,但它只适用于firefox

答案 1 :(得分:1)

<html>

<head></head>

<body>

  <input type="file" id="openfile" />

  <br>
  <pre id="filecontents"></pre>
  <script type="text/javascript">
    document.getElementById("openfile").addEventListener('change', function() {
      var fr = new FileReader();
      fr.onload = function() {
        document.getElementById("filecontents").textContent = this.result;
      }
      fr.readAsText(this.files[0]);
    })
  </script>
</body>
</html>

此代码有效         
        

    <script type="text/javascript">

     document.getElementById("openfile").addEventListener('change', function(){


            var fr= new FileReader();
            fr.onload= function(){

                        document.getElementById("readfile").textContent=this.result;

            }

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


     })

    </script>

答案 2 :(得分:0)

<html>
  <head>
    <title>reading file</title>
   </head>
<body>

&#13;
&#13;
var input = document.getElementById("myFile");
var output = document.getElementById("output");

input.addEventListener("change", function () {
  if (this.files && this.files[0]) {
    var myFile = this.files[0];
    var reader = new FileReader();
    
    reader.addEventListener('load', function (e) {
      output.textContent = e.target.result;
    });
    
    reader.readAsBinaryString(myFile);
  }
});
&#13;
<input type="file" id="myFile">
<hr>
<textarea style="width:500px;height: 400px" id="output"></textarea>
&#13;
&#13;
&#13;

<input type="file" id="myFile">
<hr>
<!--<div style="width: 300px;height: 0px" id="output"></div>-->
<textarea style="width:500px;height: 400px" id="output"></textarea>

<script>
var input = document.getElementById("myFile");
var output = document.getElementById("output");

input.addEventListener("change", function () {
  if (this.files && this.files[0]) {
    var myFile = this.files[0];
    var reader = new FileReader();

    reader.addEventListener('load', function (e) {
      output.textContent = e.target.result;
    });

    reader.readAsBinaryString(myFile);
  }
});
</script>
  </body>
</html>