subanki
subanki

Reputation: 1429

How to open and save text in html to a file using javascript in HTML

i have a textarea and two buttons

like

<form name="form1">
<textarea name="text1"> HTML Codes goes here </textarea>
<input type="button"> Open File
<input type="button"> Save File
</form>

when i click on "save" button i want the text in textarea to be saved (i want it to pop up the "save as" dialog box)

When i click on "open" , it should allow me to choose any html or textfile... and load the text in the textfile/htmlcode into my textarea.

Found this code in http://www.dynamicdrive.com/forums/archive/index.php/t-10532.html

  <html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>

<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>  
</form> 

</body>
</html>

this would work if it porvides the user the choice to save the file ...and i forgot to say that all files are in the client computer.

Thanx in Advance

-Miss Subanki

Upvotes: 5

Views: 29442

Answers (3)

JC Leyba
JC Leyba

Reputation: 520

You can save a file with Javascript, but you have to use execcommand and then you'd be limited to Internet Explorer.

document.execCommand('SaveAs', true);

Upvotes: 1

user372551
user372551

Reputation:

This is possible only in IE, since the ActiveXObject has access to files (Read/Write). so, you can do it

I still remember, I tried it once and got succeeded

But Remember it only works in IE

Upvotes: -1

Christian
Christian

Reputation: 28125

Saving - You have to do that server-side, but it isn't difficult; in PHP you would just force some HTTP headers before outputting the data:

// set the content type
header('Content-type: text/plain');
// force save as dialog (and suggest filename)
header('Content-Disposition: attachment; filename="download.txt"');
// next echo the text
echo $_POST['text'];

Opening - You have to handle the uploaded data server-side, unless you use some proprietary (albeit "open") API like in firefox.

Upvotes: 3

Related Questions