How to read a local text file?

前端 未结 20 2305
北恋
北恋 2020-11-21 05:28

I’m trying to write a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.

20条回答
  •  遇见更好的自我
    2020-11-21 06:06

    Adding to some the above answers, this modified solution worked for me.

    
    

    ....

    let fileInput  = document.getElementById('file-upload-input');
    let files = fileInput.files;
    
    //Use createObjectURL, this should address any CORS issues.
    let filePath = URL.createObjectURL(files[0]);
    

    ....

    function readTextFile(filePath){
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", filePath , true);
        rawFile.send(null);
    
        rawFile.onreadystatechange = function (){
            if(rawFile.readyState === 4){
                if(rawFile.status === 200 || rawFile.status == 0){
                    var allText = rawFile.responseText;
                    console.log(allText);
                }
            }
        }     
    }
    

提交回复
热议问题