使用JavaScript创建文本文件

14

我正在使用以下代码使用Javascript创建文本文件,但它不起作用。

<html>
    <head>
        <script language="javascript">
            function WriteToFile()
            { 
                var txt = new ActiveXObject("Scripting.FileSystemObject");
                var s = txt.CreateTextFile("11.txt", true);
                s.WriteLine('Hello');
                s.Close();
             }
         </script>
    </head>
   <body onLoad="WriteToFile()">
   </body>
</html>

我认为您需要安装ActiveX插件,您使用的是哪个浏览器? - Faraona
5
ActiveX仅适用于微软浏览器,如果想要跨浏览器兼容性,你不应该使用它。至于写入文件,这是有很好的理由不被允许的。想象一下,如果允许这样做,在浏览随意的网站时你的硬盘会被擦除多少次。 - Faraona
5个回答

7
试试这个:
<SCRIPT LANGUAGE="JavaScript">
 function WriteToFile(passForm) {

    set fso = CreateObject("Scripting.FileSystemObject");  
    set s = fso.CreateTextFile("C:\test.txt", True);
    s.writeline("HI");
    s.writeline("Bye");
    s.writeline("-----------------------------");
    s.Close();
 }
  </SCRIPT>

</head>

<body>
<p>To sign up for the Excel workshop please fill out the form below:
</p>
<form onSubmit="WriteToFile(this)">
Type your first name:
<input type="text" name="FirstName" size="20">
<br>Type your last name:
<input type="text" name="LastName" size="20">
<br>
<input type="submit" value="submit">
</form> 

这只能在IE上运行


您需要安装ActiveX插件。 - Faraona
我正在使用Mac系统,我刚刚将“set s = fso.CreateTextFile(“C:\ test.txt”,True);”替换为“set s = fso.CreateTextFile(“file / test.txt”,True);”,但文件没有被创建。 - user475685
6
我认为在Safari和Firefox浏览器上无法使用JavaScript完成此操作。你必须寻找其他解决方案。 - Faraona

4

3

从网页上来说这是不起作用的,因为IE限制了该对象的使用。


2
<textarea id="content" placeholder="Content..." cols="32" rows="7">Lorem ipsum
dolor sit amet!</textarea><br>
<input type="text" id="fileName" placeholder="download.txt">
<button type="button" id="download">Download</button>

<script>
// DOM utility functions:

const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);


// Create file and download it:

const createAndDownload = (content, download = "download.txt", type = "text/plain") => {
  const file = new Blob([content], { type });
  const href = URL.createObjectURL(file);
  const elAnchor = elNew("a", { href, download });
  el("body").append(elAnchor);
  elAnchor.click();
  elAnchor.remove();
  URL.revokeObjectURL(href);
};


// Usage example:

el("#download").addEventListener("click", () => {
  const text = el("#content").value;
  const name = el("#fileName").value;
  createAndDownload(text, name, "text/plain");
});
</script>

-2

你必须指定保存文件的文件夹,并且该文件夹必须存在,否则会出现错误。

var s = txt.CreateTextFile("c:\\11.txt", true);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接