1

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

1

2 Answers 2

5

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);​
Sign up to request clarification or add additional context in comments.

2 Comments

I used code similar to this before, apparently I had some errors. This helped alot, thank you!
Great example written in pure JS! Thanks
4

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

4 Comments

That is actually what I had tried before. It didn't seem to work properly.
It is supported in modern browsers only. Check xdazz's demo
this works, but not locally (on chrome atleast). I forgot to update everyone on that. When i tried it on a webhost it was perfectly fine.
@user1276567 for accessing local files in Chrome you must start Chrome with this switch: chrome --disable-web-security

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.