简体   繁体   English

使用javascript获取文本文件内容

[英]Get text file content using javascript

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. 我已经尝试使用javascript打开文本文件并获取他的名字和他的内容,所以现在我被困在字符串,因为我使用输入类型文件来获取目录/路径。

Anyway, my question what is wrong in the next code, and how can i get text file content using javascript? 无论如何,我的问题是下一个代码有什么问题,我怎样才能使用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). 编辑:我也想在输入文件中禁用所有文件opition(*)到文本文件(.txt)。

Thanks! 谢谢!

Modern browsers implementing FileReader can do this. 实现FileReader现代浏览器可以做到这一点。 To test your browser check if window.FileReader is defined. 要测试浏览器,请检查是否定义了window.FileReader

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). 在我的例子中,我只需将文件拖到HTML元素上,该元素在此处引用为panel.in1但您也可以使用<input type="file" /> (请参阅下面的参考资料)。

 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 . 它是reader.onloadend函数,它获取您在事件处理程序中恢复的文件的文本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 我从MDN获得了大部分关于如何执行此操作的机制: https//developer.mozilla.org/en-US/docs/Using_files_from_web_applications

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

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