最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Reading a text file using Javascript - Stack Overflow

programmeradmin2浏览0评论

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>

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>

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>

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>
Share Improve this question edited May 26, 2015 at 8:53 Cobra asked May 26, 2015 at 8:30 CobraCobra 731 gold badge3 silver badges9 bronze badges 11
  • 4 Java has nothing to do with JavaScript – Dragondraikk Commented May 26, 2015 at 8:31
  • 1 document.getElementById("\\file.txt") does not exist in your document, so you'll get an exception when you try to read from it. Look at your JavaScript console. – Quentin Commented May 26, 2015 at 8:46
  • 1 Does this document.getElementById("\\file.txt").files[0] line getting any element. I don't think so. What are trying to to here? – sachin.ph Commented May 26, 2015 at 8:46
  • 1 "load", startRead() { }, false is a syntax error, so you'll get an exception when you try to compile that code. Look at your JavaScript console. – Quentin Commented May 26, 2015 at 8:46
  • 1 Does the code snippet below work as opposed to the one above? – Sebastian Simon Commented May 26, 2015 at 8:59
 |  Show 6 more comments

3 Answers 3

Reset to default 11

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

Live Demo (With Input File)

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

Without Input File

Function

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

And to test it

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

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

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

this code works

    <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>
<html>
  <head>
    <title>reading file</title>
   </head>
<body>

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);
  }
});
<input type="file" id="myFile">
<hr>
<textarea style="width:500px;height: 400px" id="output"></textarea>

<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>
发布评论

评论列表(0)

  1. 暂无评论