簡體   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