Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 429
espresso_coffee Avatar asked Oct 04 '16 14:10

espresso_coffee


1 Answers

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
like image 99
adeneo Avatar answered Oct 30 '22 08:10

adeneo