[英]How to open and save text in html to a file using javascript in HTML
我有一個textarea和兩個按鈕
喜歡
<form name="form1">
<textarea name="text1"> HTML Codes goes here </textarea>
<input type="button"> Open File
<input type="button"> Save File
</form>
當我點擊“保存”按鈕時,我希望保存textarea中的文本(我希望它彈出“另存為”對話框)
當我點擊“打開”時,它應該允許我選擇任何html或文本文件...並將textfile / htmlcode中的文本加載到我的textarea中。
在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>
如果它為用戶提供保存文件的選擇,這將有效...我忘了說所有文件都在客戶端計算機中。
Thanx提前
-Miss Subanki
保存 - 你必須做服務器端,但這並不困難; 在PHP中,您只需在輸出數據之前強制使用一些HTTP頭:
// 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'];
打開 - 你必須處理上傳的數據服務器端,除非你使用像Firefox一樣的專有(雖然“開放”)API。
您可以使用Javascript保存文件,但必須使用execcommand,然后您將被限制為Internet Explorer。
document.execCommand('SaveAs', true);
這僅在IE中可行,因為ActiveXObject
可以訪問文件(讀/寫)。 所以,你可以做到
我還記得,我嘗試過一次並取得了成功
但請記住它只適用於IE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.