[英]How to read the first line of .txt file?
can anyone one help how to read the first line of .txt file? 任何人都可以帮助如何阅读.txt文件的第一行? I have input type file that upload example.txt then I would like to grab the first line from that code.
我有上传example.txt的输入类型文件,然后我想抓住该代码的第一行。 I tried something like this:
我试过这样的事情:
<input type="file" id="fileUpload" name="fileUpload"/> MyTest.txt //file name
function confirmFileSubmit(){
var fileName = $('#fileUpload').val();
alert($('#fileUpload').split('\n')[0]);
}
After I run my code this just outputted file name in alert box. 运行我的代码后,这只是在警告框中输出文件名。 I'm not sure how I can read the content of the file.
我不确定如何阅读文件的内容。 If anyone can help please let me know.
如果有人可以提供帮助,请告诉我。
You'll need the FileReader for that 你需要FileReader
function confirmFileSubmit(){
var input = document.getElementById('fileUpload'); // get the input
var file = input.files[0]; // assuming single file, no multiple
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result; // the entire file
var firstLine = text.split('\n').shift(); // first line
console.log(firstLine); // use the console for debugging
}
reader.readAsText(file, 'UTF-8'); // or whatever encoding you're using
// UTF-8 is default, so this argument
} // is not really needed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.