如何使用JavaScript / HTML5创建.txt文件? [英] How to create .txt file using JavaScript / HTML5?

查看:272
本文介绍了如何使用JavaScript / HTML5创建.txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

此代码应该工作,试试这个,如果这不工作,那么它可能是你的浏览器的问题:

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

//如果我们要替换之前生成的文件,我们需要
//手动撤销对象URL以避免内存泄漏。

$ b 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);
})();

和HTML:

 < textarea id =textbox>在此键入内容< / textarea> < button id =create>建立档案< / button> 

取自此小提琴:

< a href =http://jsfiddle.net/uselesscode/qm5ag/ =nofollow noreferrer> http://jsfiddle.net/uselesscode/qm5ag/


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.

解决方案

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:

<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/

这篇关于如何使用JavaScript / HTML5创建.txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆