How do I read in a local text file with javascript

2019-01-15 22:27发布

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 a test taking program. The file should not be uploaded, and only read locally. It is okay if the solution only works on chrome and firefox.

I have tried looking through many things, but so far what I seem to see is that it is not possible for security reasons, or it is but it doesn't work properly. I

This is my current code: http://pastebin.com/uKvEfvZZ

2条回答
趁早两清
2楼-- · 2019-01-15 22:31

Use HTML5 file API. It allows you to select and read files locally.

查看更多
Root(大扎)
3楼-- · 2019-01-15 22:43

Here is a demo.

html:

<input type="file" id="fileinput" multiple />

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);​
查看更多
登录 后发表回答