使用Javascript读取文本文件 [英] Reading a text file using Javascript

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

问题描述

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

The following code should read the content of a text file which is in the current directory upon load, and display it on the html page. I tried modifying by my self. But it does not give an output. Is there an easier way to get this result using another method? or please help figure out what is wrong with this code?

<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文件时,它将读取当前目录中的文本文件并显示内容.

Given below is the code which I modified to get the above code. My intention was. As I open the html file it would read the text file which is in the current directory and display the content.

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

推荐答案

尝试一下此片段,我刚刚尝试过,它可以工作:)!

Try this snippet, I just tried and it works :)!

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!"
    }
});

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

功能

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中有效

Notice: I tried it, but it works only in firefox

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

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