user2014905 user2014905 - 1 year ago 151
Javascript Question

Javascript read text file from current directory

How to read text file (text1.txt) from current directory using javascript without jquery. I tried the following code.

var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);

Answer Source

The FileReader API is usually used to read files selected via the an <input type="file">. It cannot read arbitrary files. The readAsText method expects to receive with a Blob or a File object, not a string containing a file name.

To read files that are siblings of the HTML document, use XMLHttpRequest. This will reliably work if you load the document over HTTP(S). If you are using a local HTML document (via a file: URI) then security restrictions in many browsers will prevent it from working (and you should run a local web server instead).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download