Thursday, May 29, 2008

Reading a file from local file system using javascript

Reading a file into javascript variable is a issue anyone can face while developing client side application.

The problem has different solution depending on platform/browser

Solution

1) Windows/IE
: Use the available FileSystemObject. It allows one to read and write files from local machine.

2) Firefox
: It does not have a object corresponding to FileSystemObject in IE. So we rely on XMLHTTPREQUEST Object provided. Our strategy here is to send the file to the server. On server read the file and flush the content to the client. On client side we can get the file contents in xmlhttprequest.responseText property.

3) Applet:
This solution makes use of Java Applet which allows you to read the local files.

Example of 2nd method using PHP as scripting language

1) From the client side write a form having a file upload utility.

2)Send the file to the server.

3) On sever side read that file and flush the contents

PHP Code

if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "
";
}
else
{
echo "
";
$file = fopen($_FILES["file"]["tmp_name"], "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "
";
}
fclose($file);
}

4) On client side read it as
var fileContent=xmlhttprequest.responseText


Thats it!! you are done.

1 comment:

Haris said...

if u r using js +applet is it possible for accessing portable devices or cd drives ...?