簡體   English   中英

如何閱讀.txt文件的第一行?

[英]How to read the first line of .txt file?

任何人都可以幫助如何閱讀.txt文件的第一行? 我有上傳example.txt的輸入類型文件,然后我想抓住該代碼的第一行。 我試過這樣的事情:

<input type="file" id="fileUpload" name="fileUpload"/> MyTest.txt //file name

function confirmFileSubmit(){
    var fileName = $('#fileUpload').val();
    alert($('#fileUpload').split('\n')[0]);
} 

運行我的代碼后,這只是在警告框中輸出文件名。 我不確定如何閱讀文件的內容。 如果有人可以提供幫助,請告訴我。

你需要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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM