Get the contents of a text file using javascript

I tried using javascript to open a text file and get its name and its content, so right now I am stuck in a line because I used an input type file to get the directory / path.

Anyway, my question is what is wrong in the following code, and how can I get the contents of a text file 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 want to disable in the input file all files (*) only for text files (.txt).

Thanks!

+4
source share
1 answer

Modern browsers that implement FileReader can do this. To check your browser, check if window.FileReader .

Here is the code I wrote just this morning to do just that. In my case, I just drag and drop the file onto the HTML element called panel.in1 here, but you can also use <input type="file" /> (see link 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); } 

This is the reader.onloadend function, which receives the text of the file that you are restoring in the event handler, like 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

+12
source

Source: https://habr.com/ru/post/1484452/


All Articles