Reading a file from 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 guys. You are Done.

This entry was posted in PHP, javascript and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*