简体   繁体   English

使用javascript从文本文件读取值

[英]Reading values from text file using javascript

  • I have a text file in my local machine. 我的本地计算机上有一个文本文件。
  • And i have a button in jsp page. 而且我在jsp页面中有一个按钮。
  • On click of the button, i need to get the text file contents. 在单击按钮时,我需要获取文本文件的内容。
  • And the file has n number of contents. 并且该文件具有n个内容。

Can anyone give me javascript function to achieve this. 谁能给我JavaScript函数来实现这一目标。

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. 您应该看一下FileAPI-一种HTML 5 Javascript附加功能,它允许JavaScript通过文件输入读取文件内容。

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 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. 如果没有FileAPI,您仍然可以使用带有target =“ some iframe”形式的文件输入字段-然后让服务器上传文件并返回文本。 ( FormData allows uploading files in Ajax but it is not supported in all browsers ). (FormData允许在Ajax中上传文件,但并非所有浏览器都支持它)。

So File API is your way to go Here is how you do it with File API 因此,File API是您的理想之路以下是使用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 ) 您还可以实现拖放界面(例如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])});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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