简体   繁体   中英

Reading values from text file using javascript

  • 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.

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])});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM