Entry
How can I read a file selected with the INPUT TYPE="file" element?
Feb 26th, 2001 14:08
Martin Honnen,
With the normal security settings client side JavaScript can not read
files of the local file system. If security settings are low enough
however the following code works with NN4 and IE4+:
<HTML>
<HEAD>
<SCRIPT>
function readFile (fileName) {
if (document.layers && navigator.javaEnabled()) {
netscape.security.PrivilegeManager.enablePrivilege('UniversalFileRead');
var bfr = new java.io.BufferedReader(new
java.io.FileReader(fileName));
var line;
var content = '';
while ((line = bfr.readLine()) != null)
content += line + java.lang.System.getProperty('line.separator');
return content;
}
else if (document.all) {
var fso = new ActiveXObject('Scripting.FileSystemObject');
var fs = fso.OpenTextFile(fileName);
var result = fs.ReadAll();
return result;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="formName">
<INPUT TYPE="file" NAME="fileName">
<INPUT TYPE="button" VALUE="show"
ONCLICK="this.form.fileContent.value =
readFile(this.form.fileName.value)"
>
<BR>
<TEXTAREA NAME="fileContent" ROWS="20" COLS="80" WRAP="off"></TEXTAREA>
</FORM>
</BODY>
</HTML>