How do I read in a local text file with javascript?

后端 未结 2 598
鱼传尺愫
鱼传尺愫 2020-12-07 04:40

I am trying to use to select a file locally and read the text in it line by line to interpret it. My program is meant to read a text file and read questions from it to make

2条回答
  •  生来不讨喜
    2020-12-07 05:19

    Here is a demo.

    html:

    
    

    js:

    function readMultipleFiles(evt) {
        //Retrieve all the files from the FileList object
        var files = evt.target.files;
    
        if (files) {
            for (var i = 0, f; f = files[i]; i++) {
                var r = new FileReader();
                r.onload = (function (f) {
                    return function (e) {
                        var contents = e.target.result;
                        alert(contents);
                    };
                })(f);
                r.readAsText(f);
            }
        } else {
            alert("Failed to load files");
        }
    }
    document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);​
    

提交回复
热议问题