6

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>
Cobra
  • 73
  • 1
  • 3
  • 8
  • 4
    Java has nothing to do with JavaScript – Dragondraikk May 26 '15 at 08: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 May 26 '15 at 08: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 May 26 '15 at 08: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 May 26 '15 at 08:46
  • I posted the original code. That is what I modified to get this code. My requirement I have mentioned along with it. What I need is for the script to read the text file on load and display the text content. – Cobra May 26 '15 at 08:54
  • 1
    Does the code snippet below work as opposed to the one above? – Sebastian Simon May 26 '15 at 08:59
  • yes the one below woks perfectly fine. The one I tried modifying for my requirement is the one above which does not work. – Cobra May 26 '15 at 09:07
  • It should work if you’d replace `window.addEventListener("load", startRead() { }, false);` by `window.addEventListener("load", startRead);`, if you’d include the file input field with the ID `file` and used `document.getElementById('file')` instead of …`\file`…. – Sebastian Simon May 26 '15 at 09:09
  • I did those change. It's not giving an output. I think because it doesn't know which file to read from, im not sure. Is there away to specify or hard code a file name or path so it will read only that. – Cobra May 26 '15 at 09:15
  • No, that’s not possible. The files are accessible through the `files` property only. You should see at least a `FileList` object when putting `console.log(file.files[0])` in the `startRead` function and looking into the browser console. Is it really `getElementById('file')` and ``? – Sebastian Simon May 26 '15 at 09:21
  • is there are way to hard code the id="file" parameter so . When i load the html file. The text file automatically gets read.? – Cobra May 26 '15 at 09:50

3 Answers3

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

Sid
  • 14,176
  • 7
  • 40
  • 48
  • I'm new to javascript. what should I put as the input file ID? is it a file path? Does it have a specific format? – Cobra May 26 '15 at 09:31
  • I added a link with a Live Demo, just have a look :)! @Cobra – Sid May 26 '15 at 09:34
  • I just tried it but it's not giving an output :/ @Assa – Cobra May 26 '15 at 09:48
  • Have you tried the live demo? Which browser are you using? – Sid May 26 '15 at 09:50
  • yes I tried it, but no output. I'm using Mozilla Firefox version 37.0.1 and I just tried it on chrome as well, same result. – Cobra May 26 '15 at 09:52
  • Well it is strange, because for me it's working. Anybody else can try it? – Sid May 26 '15 at 09:55
  • what is the output you get? an alert box with the file content?? can you take a look at my earlier code and see if there is a possibility of getting that to work? @Assa – Cobra May 26 '15 at 09:57
  • that works perfectly fine. I have a few more questions if you don't mind. Is there away to display the content onload? without having to click the link? – Cobra May 26 '15 at 10:24
  • yeah sure, just call the function on , mark as answered if you don't mind :)! – Sid May 26 '15 at 10:30
  • yes i just did it thank you. works like a charm (y) :) – Cobra May 26 '15 at 10:35
  • Pleasure is mine :)! @Cobra – Sid May 26 '15 at 10:38
  • I have another question. Is there script that could get this file location automatically and pass it to readTextFile(). Assume that the text file is in the current directory and you can predefine the name of the text file as well. Test @Assa – Cobra May 28 '15 at 07:00
  • @Cobra Use a variable to store the name of the file! :) – Sid May 28 '15 at 07:41
  • I managed to figure it out thanks. Another question if you don't mind. Say I want to run my script every 60 seconds. How will I get around this? @Assa – Cobra May 29 '15 at 08:07
  • function sendData(data){ var request = new XMLHttpRequest(); request.open("POST", "inde.php", true); request.setRequestHeader("Content-type","text/plain;charset=UTF-8"); request.setRequestHeader("Content-length", data.length); request.send(data); } @Assa I'm using this function to post 'data' plain text to a php page. it doesn't seam to be doing the job. I just want this data to be echoed on a php page. Could you give me a php that could do this? and tell if there is anything wrong in this js code – Cobra Jun 03 '15 at 04:41
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>

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>
Ramlal S
  • 1,573
  • 1
  • 14
  • 34
0
<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>
Poornachander K
  • 603
  • 5
  • 4