用javascript创建一个文本文件

vof42yt1  于 2023-01-24  发布在  Java
关注(0)|答案(5)|浏览(196)

我正在使用下面的代码创建一个使用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>
8xiog9wr

8xiog9wr1#

试试这个:

<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上起作用

zsohkypk

zsohkypk2#

这样做效果更好:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

http://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx

mqkwyuun

mqkwyuun3#

在网页上,由于IE限制使用该对象,因此无法执行此操作。

ghhkc1vu

ghhkc1vu4#

<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>
bvjveswy

bvjveswy5#

你必须指定你保存它的文件夹,它必须存在,在其他情况下,它会抛出一个错误。

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

相关问题