Reading a text file using Javascript

2019-07-22 04:29发布

问题:

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>

回答1:

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



回答2:

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


回答3:

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