最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to read the first line of .txt file? - Stack Overflow

programmeradmin3浏览0评论

can anyone one help how to read the first line of .txt file? I have input type file that upload example.txt then I would like to grab the first line from that code. 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.

can anyone one help how to read the first line of .txt file? I have input type file that upload example.txt then I would like to grab the first line from that code. 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.

Share Improve this question asked Oct 4, 2016 at 14:47 espresso_coffeeespresso_coffee 6,11012 gold badges93 silver badges220 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

You'll need the FileReader for that

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
发布评论

评论列表(0)

  1. 暂无评论