1
  • I have a text file in my local machine.
  • And i have a button in jsp page.
  • On click of the button, i need to get the text file contents.
  • And the file has n number of contents.

Can anyone give me javascript function to achieve this.

5

1 Answer 1

1

You should specify in your question that you want client side file reading as I see a lot are referring to server side reading.

You should have a look in FileAPI - an HTML 5 Javascript addition that allows JavaScript to read file content via the file input.

I am working on code example for you - but here is a good site you should read

http://www.htmlgoodies.com/beyond/javascript/read-text-files-using-the-javascript-filereader.html#fbid=4Fhi9T4mEAA

Without FileAPI - you can still use the file input field in form with target="some iframe" - then let the server upload the file and return the text. ( FormData allows uploading files in Ajax but it is not supported in all browsers ).

So File API is your way to go Here is how you do it with File API

<input type="file"/>
<script>
$(function(){
            $("input").change(function(e){
                    console.log(["file changed",e]);
                var myFile = e.target.files[0];
                var reader = new FileReader();
                reader.onload = function(e){
                    console.log(["this is the contents of the file",e.target.result]);
                };
                reader.readAsText(myFile)

            });
        }
)
</script>

You can also implement a drag/drop interface (like google gmail has )

        $("div").on("dragover",function(e){
            e.dataTransfer = e.originalEvent.dataTransfer;
                e.stopPropagation();
                e.preventDefault();
                e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.

        }).on("drop",function(e){
                    e.dataTransfer = e.originalEvent.dataTransfer;
                    e.stopPropagation();
                    e.preventDefault();
                    console.log(["selected files", e.dataTransfer.files])});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.