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.
Thursday, May 29, 2008
Monday, May 26, 2008
Export to CSV + PHP
On Client
From the client send the string in csvContent field.
input name="csvContent " type="hidden"
Send the fileName in fileName field.
input name="fileName " type="text"
On the Server
$Content = $_POST['csvContent'];
$filename=$_POST['fileName'];
header('Content-Disposition: attachment; filename='.$filename);
header("Content-type: application/text");
echo $Content;
Set header :
1. Content-Disposition:attachment; filename='fileName'
2. Content-type:application/text
Write the content to the browser.
Result : It will open a save-as dialog on the browser.
From the client send the string in csvContent field.
input name="csvContent " type="hidden"
Send the fileName in fileName field.
input name="fileName " type="text"
On the Server
$Content = $_POST['csvContent'];
$filename=$_POST['fileName'];
header('Content-Disposition: attachment; filename='.$filename);
header("Content-type: application/text");
echo $Content;
Set header :
1. Content-Disposition:attachment; filename='fileName'
2. Content-type:application/text
Write the content to the browser.
Result : It will open a save-as dialog on the browser.
Subscribe to:
Posts (Atom)