3

i have the following to read a local file and display,

       <html>
       <head>
       <script> 
             function readfile() {
        document.getElementById('iframe').contentDocument.body.firstChild.innerHTML;
  }
     </script>
         </head>
        <body>
     <iframe id='iframe' src='txt2.txt' onload='readfile()'> </iframe>
     <input type="file" id="fileinput" />  
     </body>
    </html>

but here you can see i have already given the file path as 'txt2.txt', but i don't want to give the file name beforehand, instead i want to load the file and display its contents using input type="file", how to do this without using ajax ?

3
  • 1
    I don't think you can read a file locally. Really, all you can do is POST a file to a web server. Maybe some sort of HTML5, Flash, or Silverlight component could be used? Commented Sep 25, 2013 at 23:54
  • You can push the content as part of the web page itself, for example all the elements Commented Sep 26, 2013 at 0:00
  • possible duplicate of Javascript, how to read local file? Commented Sep 26, 2013 at 0:09

2 Answers 2

11

The below code will browse a file and copy the content to a textarea:

   <input type="file" id="fileinput" />
    <script type="text/javascript">
      function readSingleFile(evt) {
        //Retrieve the first (and only!) File from the FileList object
        var f = evt.target.files[0]; 

        if (f) {
          var r = new FileReader();
          r.onload = function(e) { 
              var contents = e.target.result;
            alert( "Got the file.\n" 
                  +"name: " + f.name + "\n"
                  +"type: " + f.type + "\n"
                  +"size: " + f.size + " bytes\n"
                  + "starts with: " + contents.substr(1, contents.indexOf("\n"))
            );  
            document.getElementById('area').value=  contents;
          }
          r.readAsText(f);

        } else { 
          alert("Failed to load file");
        }
      }

      document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
    </script>

    <textarea rows=20 id="area"></textarea>
Sign up to request clarification or add additional context in comments.

Comments

0

Reading local files from the browser is not allowed - This is to prevent websites reading files and stealing your information.

Please see the second post (answer) for more information: Javascript, how to read local file?

Being able to read a local file from your browser would be a major breach of security

Most browsers will not let you read local files even if the page originated from your local filesystem.

You can however try the HTML5 file API.

1 Comment

Is that true even if the page is in the same local filesystem?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.