如何使用 JavaScript / HTML5 创建 .txt 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31048215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:07:05  来源:igfitidea点击:

How to create .txt file using JavaScript / HTML5?

javascripthtml

提问by abc

I am new to javascript . all codes available on the internet related to create text file using javascript is not working in my laptop. can anybody give me idea or with possible code.

我是 javascript 新手。互联网上所有与使用 javascript 创建文本文件相关的代码在我的笔记本电脑上都不起作用。任何人都可以给我想法或可能的代码。

回答by Web Develop Wolf

This code should work, give this a try and if this doesn't work then it may be an issue with your browser:

此代码应该可以工作,请尝试一下,如果这不起作用,则可能是您的浏览器有问题:

(function () {
var textFile = null,
  makeTextFile = function (text) {
    var data = new Blob([text], {type: 'text/plain'});

    // If we are replacing a previously generated file we need to
    // manually revoke the object URL to avoid memory leaks.
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }

    textFile = window.URL.createObjectURL(data);

    return textFile;
  };


  var create = document.getElementById('create'),
    textbox = document.getElementById('textbox');

  create.addEventListener('click', function () {
    var link = document.getElementById('downloadlink');
    link.href = makeTextFile(textbox.value);
    link.style.display = 'block';
  }, false);
})();

And the HTML:

和 HTML:

<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> 
<a download="info.txt" id="downloadlink" style="display: none">Download</a>

Taken from this Fiddle:

取自这个小提琴:

http://jsfiddle.net/uselesscode/qm5ag/

http://jsfiddle.net/uselesscode/qm5ag/

回答by Ismael EL ATIFI

A very fast and easy solution is to use FileSaver.js:
https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js

一个非常快速和简单的解决方案是使用FileSaver.jshttps: //raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js

Then it takes only 2 lines of code to download a txt file :

那么下载一个txt文件只需要2行代码:

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});

saveAs(blob, "hello world.txt");


This code example will display a dialog box to download a file named "hello world.txt" containing the text "Hello, world!". Just replace this by the file name and the text content of your choice !


此代码示例将显示一个对话框,用于下载名为“hello world.txt”的文件,其中包含文本“Hello, world!”。只需将其替换为您选择的文件名和文本内容即可!