简体   繁体   中英

How to read the first line of .txt file?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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