如何使用 javascript 将表单数据附加和保存到 txt 文件

How to append and save form data to txt file using javascript

我有这个 html 代码:

<form  action="" method="post" id="formToSave">
                <h1>Subscribe For Latest Blogs</h1>
                <p>Please subscribe in my website using your email address for latest updates about my blogs and publications.</p>
                <div class="email-box">
                    <i class="fas fa-envelope"></i>
                    <input class="tbox" type="email" name="email" id ="email" value="" placeholder="Enter Your Email Address">
                    <m><button class="btn" type="submit" name="button" onclick="saveFile()" >Subscribe</button></m>
                </div>
            </form>

还有这个 javascript 代码:

<script>
    let saveFile = () => {
        const email = document.getElementById('email');
        let data = email.value;
        const textToBLOB = new Blob([data], { type: 'text/plain' });
        }
</script>

我想将电子邮件地址表单数据保存到一个文本文件,并将更多电子邮件地址附加到该文件。接下来我该做什么?

首先,我建议在服务器上执行此操作,因为浏览器 javascript 无法访问文件系统并且无法将新文本附加到文件中。但是,如果您需要一个包含仅由一个客户提供的电子邮件的文本文件,则以下代码可能会有所帮助。请记住,这仅适用于客户端,对于没有服务器的订阅系统无济于事。

const emailsList = []

function addEmailToList() {
  const email = document.getElementById('email')
  const { value } = email
  emailsList.push(value)
}

function downloadFile() {
  const textFile = btoa(emailsList.join('\n'))
  const saveElement = document.createElement('a')
  saveElement.href = `data:text/plain;base64,${textFile}`
  saveElement.download = 'myList.txt'
  document.body.appendChild(saveElement)
  saveElement.click()
  document.body.removeChild(saveElement)
}
<form action="" method="post" id="formToSave">
      <h1>Subscribe For Latest Blogs</h1>
      <p>Please subscribe in my website using your email address for latest updates about my blogs and publications.</p>
      <div class="email-box">
        <i class="fas fa-envelope"></i>
        <input class="tbox" type="email" name="email" id="email" value="" placeholder="Enter Your Email Address" />
        <m><button class="btn" type="button" name="button" onclick="addEmailToList()">Subscribe</button></m>
        <m><button class="btn" type="button" name="button" onclick="downloadFile()">Download TextFile</button></m>
      </div>
    </form>