Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<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;
        }
    }
</script>
</head>
<body>
<form method="get" action="#"  >
    <input type="file" accept="text/plain" id="txt" />
    <input type="submit" value="Display Text File" onclick="display();" />
</form>
<a href="#" id="filename"></a>
</body>
</html>

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

Thanks!

like image 244
copypaste Avatar asked Dec 12 '22 14:12

copypaste


1 Answers

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 : https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

like image 133
HBP Avatar answered Dec 28 '22 16:12

HBP