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
    Hiya, this might help: http://stackoverflow.com/questions/7466387/read-2-text-files-with-javascript ; cheers! – Tats_innit Mar 18 '12 at 06:10

2 Answers2

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);​
xdazz
  • 158,678
  • 38
  • 247
  • 274
4

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

Nemoy
  • 3,347
  • 1
  • 15
  • 14
  • That is actually what I had tried before. It didn't seem to work properly. –  Mar 18 '12 at 06:14
  • It is supported in modern browsers only. Check xdazz's demo – Nemoy Mar 18 '12 at 06:16
  • 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. –  Feb 06 '13 at 08:17
  • @user1276567 for accessing local files in Chrome you must start Chrome with this switch: chrome --disable-web-security – pilau Feb 27 '13 at 12:43