Question: How do I read a file into a JavaScript variable?
Answer: Depending on the environment in which your script runs and where the file resides, your options include the following:
Below we'll discuss the latter option -
a Java "helper" applet that reads files for your script. One of the possible reading mechanisms implementing this technique 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; }
Copyright © 1999-2011, JavaScripter.net.