JS 将文本保存为一个.txt文件

25 min read

在 JavaScript 中,可以使用 BlobURL.createObjectURL 将文本保存为 .txt 文件。以下是一个简单的示例:

function saveTextAsFile() {
  const textToSave = "Hello, World!";
  const textToSaveAsBlob = new Blob([textToSave], {type: "text/plain"});
  const fileNameToSaveAs = "example.txt";

  const downloadLink = document.createElement("a");
  downloadLink.download = fileNameToSaveAs;
  downloadLink.innerHTML = "Download File";

  if (window.webkitURL !== null) {
    downloadLink.href = window.webkitURL.createObjectURL(textToSaveAsBlob);
  } else {
    downloadLink.href = window.URL.createObjectURL(textToSaveAsBlob);
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
  }

  downloadLink.click();
}

function destroyClickedElement(event) {
  document.body.removeChild(event.target);
}

saveTextAsFile();

这段代码会创建一个包含 "Hello, World!" 文本的 .txt 文件,并将其作为下载链接提供给用户。用户点击下载链接后,文件将被保存到本地。