[英]To display text from a txt file using javascript
How to read text from a txt file with one button to browse the file and other button to display text. 如何使用一个按钮浏览txt文件并使用另一个按钮显示文本来从txt文件读取文本。 Pls help me in getting the code. 请帮助我获取代码。 i have tried many codes but othing worked. 我已经尝试了许多代码,但是其他都可以。 some code was like this. 一些代码是这样的。 Thanks in advance 提前致谢
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "@":
output=output.split("\n").filter(/./.test, /\@/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
You should properly read an article like this: http://www.html5rocks.com/en/tutorials/file/dndfiles/ 您应该正确阅读如下文章: http : //www.html5rocks.com/en/tutorials/file/dndfiles/
Dont think this line is working properly: 不要以为这条线工作正常:
output=output.split("\n").filter(/./.test, /\@/).join("\n");
Try changing it to: 尝试将其更改为:
output=output.split("\n").filter(function(l) {
//return /^\@/.test(l); // Starting with @
return l.indexOf('@') > -1; // Containing @
}).join("\n");
It would be interesting to see if this would work as well: 看看这是否也将很有趣:
output=output.split("\n").filter(/\@/.test.bind(/\@/)).join("\n");
The second arguments passed to the .filter
method is the context: 传递给.filter
方法的第二个参数是上下文:
array.filter(callback[, thisObject]) array.filter(callback [,thisObject])
Get the input file, use FileReader() to read it,on file load get text that matches the pattern. 获取输入文件,使用FileReader()读取它,在文件加载时获取与模式匹配的文本。 Finally display it through "main" div. 最后通过“ main” div显示它。 Should work.. 应该管用..
HTML : HTML:
<input id="fileInput" type="file"/>
<div id="main"></div>
jQuery : jQuery的:
$(function(){
$("#fileInput").change(function(e){
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output=output.split("\n").filter(/./.test, /\@/).join("\n");
$("#main").text(output);
};
reader.readAsText(myFile)
});
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.