Reading a File
Question: How do I read a file into a JavaScript variable?
Answer:
Reading a file from JavaScript is (almost) as easy as reading a file from a Java applet.
Your script cannot read files itself; you would have to code a Java applet that
reads files for your script.
In more detail, one of the possible reading mechanisms can work like this:
- Your script calls a public method of the applet.
- The public method initiates the reading process in another thread of the applet,
and then returns.
- The reading process in another thread of the applet continues.
At the same time, the script keeps asking the applet whether the reading is complete.
- The applet finishes reading and puts the file content in a public string
variable of the applet.
- The script sees that the applet completed reading.
- The script copies the file content from the applet's public variable
into a Javascript variable.
Note that
unsigned Java/JavaScript code can read files only if the
file(s) to read and the code itself have
the same origin.
For example, if your unsigned code is published on a Web server,
it is allowed to read files from the same server only.
If your code resides on the local hard disk, it is allowed
to read files only from the same disk (at best).
If you would like to read files that have a different origin,
you'll need to sign your code.
(For more information, see Writing Files;
very similar security considerations apply to reading files whose origin
is other than that of your code.)
Here's a simple example that implements the file reading mechanism described above.
The rectangle below is a Java applet called ReadURL.class.
This applet reads the content of the chosen file into a public
variable fileContent
. When finished,
the applet sets its public variable finished
to 1.
The script in this example reads selected files that contain some topics
from this JavaScript FAQ.
The JavaScript code that starts the reading process looks as follows:
var fileContent='';
var theLocation='';
function readFileViaApplet(n) {
document.f1.t1.value='Reading in progress...';
document.ReadURL.readFile(theLocation);
setTimeout("showFileContent()",100);
}
function showFileContent() {
if (document.ReadURL.finished==0) {
setTimeout("showFileContent()",100);
return;
}
fileContent=document.ReadURL.fileContent;
document.form1.textarea1.value=fileContent;
}
JavaScripter.net.
Copyright
© 1999-2006, Alexei Kourbatov