Javascript – Get text file content using javascript


I've tried use javascript to open text file and get his name and his content, so right now I'm stuck at string, because I used input – type file to get directory / path.

Anyway, my question what is wrong in the next code, and how can i get text file content using javascript?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""">
<title>Display Text Files</title>
<script type="text/javascript">
    var str = document.getElementById('txt').value;
    function display() {
        if (str != "") {
            var filename = str.split("/").pop();
            document.getElementById('filename').innerHTML = filename;
<form method="get" action="#"  >
    <input type="file" accept="text/plain" id="txt" />
    <input type="submit" value="Display Text File" onclick="display();" />
<a href="#" id="filename"></a>

EDIT: I also wanna disable in input file the all files opition (*) to text files only (.txt).


Best Solution

Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.

Here is some code I wrote only this morning to do just this. In my case I simply drag a file onto the HTML element which is here referenced as panel.in1 but you can also use <input type="file" /> (see the reference below).

 if (window.FileReader) {
   function dragEvent (ev) {
     ev.stopPropagation (); 
     ev.preventDefault ();
     if (ev.type == 'drop') {
       var reader = new FileReader ();
       reader.onloadend = function (ev) { panel.in1.value += this.result; };
       reader.readAsText (ev.dataTransfer.files[0]);

   panel.in1.addEventListener ('dragenter', dragEvent, false);
   panel.in1.addEventListener ('dragover', dragEvent, false);
   panel.in1.addEventListener ('drop', dragEvent, false);

It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.

I got most of the mechanism on how to do this from MDN :