繁体   English   中英

如何使用纯 JavaScript 和 append 创建一个文本文件?

[英]How do I create a text file using pure JavaScript, then append to it?

我想将 append 数据转换成 txt 文件。 我查看了其他问题,所有答案都仅在 IE 中支持。 这是我到目前为止所拥有的(我是一个完整的JavaScript菜鸟,所以我对做这种事情一无所知):

var word = "单词"; //缺少代码

这里纯JavaScript代码是什么????

我在这里找到了旧答案

const createTextFile = (fileNmae, text) => {
  const element = document.createElement('a');

  element.setAttribute(
    'href',
    'data:text/plain;charset=utf-8,' + encodeURIComponent(text),
  );
  element.setAttribute('download', fileNmae);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
};

createTextFile('test.txt', 'word');


let data = "some"
let file = new Blob([data], {type: "txt"})

// Appending to the file can be mimiced this way
data = data+"Text"
file = new Blob([data], {type: "txt"})

// To Download this file
let a = document.createElement("a"), url = URL.createObjectURL(file);
a.href = url;
a.download = file;
document.body.appendChild(a);
a.click()
setTimeout(function() {
  document.body.removeChild(a);
}, 0);

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM