4

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!

copypaste
  • 175
  • 1
  • 2
  • 13
  • 3
    You can't load a local file with javascript. User would have to upload to server, then process using a server-side language, like PHP. – landons Jun 04 '13 at 16:29
  • I didn't meant to upload file.. i meant to get his content only, if it matters i can use xml also. – copypaste Jun 04 '13 at 16:30
  • You can't read local files with javascript. – BrunoLM Jun 04 '13 at 16:33
  • Browsers don't allow that for security reasons. – landons Jun 04 '13 at 16:33
  • [HTML5 file api](https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications) – epascarello Jun 04 '13 at 16:33
  • @landons What? Nonsense. There are plenty of topics on SO to read local files with JS. – Romain Braun Jun 04 '13 at 16:33
  • 1
    @RomainBraun Then I will create a website that reads /etc/passwd – landons Jun 04 '13 at 16:34
  • @BrunoLM Absolutely you can, procided that the user selects the file with a `` as in the OP's example. – apsillers Jun 04 '13 at 16:35
  • @landons The user has to specify the path, but it's possible to read files. – Romain Braun Jun 04 '13 at 16:35
  • You can read the actual contents? – landons Jun 04 '13 at 16:36
  • Besides the fact that you cannot read a user file via javascript for security reasons, you should take care not to target elements in the DOM before they are initialized. Hence, it's a good practice to add your javascript code when your window finishes loading. – mrida Jun 04 '13 at 16:36
  • @landons Yes, that is what the [`FileReader`](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) does, part of the [File API](http://www.w3.org/TR/file-upload/). – apsillers Jun 04 '13 at 16:37
  • @mrida The OP is using ``, which **can** be used to read local files, provided the user selects the file. – apsillers Jun 04 '13 at 16:40
  • 3
    I can see a couple people here need to learn about things HTML5 has to offer. :) – epascarello Jun 04 '13 at 16:41
  • @apsillers the 'document.getElementById('txt').value should be put inside the display function. (well, assuming that such approach works :D ) – mrida Jun 04 '13 at 16:47
  • Learn something new everyday. No need to be a turd about it :P – landons Jun 04 '13 at 16:48
  • @mrida Absoultely -- I don't dispute that particular part of your comment; I only object to your assertion that it's not possible to read files. – apsillers Jun 04 '13 at 16:48
  • @landons My apologies if I came across as a turd! I only meant to illustrate the threat model of the File API -- i.e., leakage of sensitive file information is *possible*, but it relies on the user acting stupidly. – apsillers Jun 04 '13 at 16:49
  • We were cool until the HTML5 comment. And now. Now we're cool. – landons Jun 04 '13 at 16:50

1 Answers1

13

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

HBP
  • 15,685
  • 6
  • 28
  • 34