加载中...

【JavaScript】将文本内容下载为文件

如何将一段文本下载为文件?用下面的代码可以实现:

function download(filename, text) {
  var element = document.createElement(''a'');
  element.setAttribute(''href'', ''data:text/plain;charset=utf-8,'' + encodeURIComponent(text));
  element.setAttribute(''download'', filename);

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

  element.click();

  document.body.removeChild(element);
}

// Start file download.
download("hello.txt","This is the content of my file :)");

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16