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:
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; }