使用JS和html5从String创建文本文件 [英] Create Text file from String using JS and html5

查看:150
本文介绍了使用JS和html5从String创建文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个字符串创建一个文本文件。目前我正在使用一个函数,它接收一个数组并将其变成字符串,然后使用该字符串,我想创建一个用户下载的本地文本文件。
i尝试使用这种方法

i want to create a text file from a string. currently i am using a function which takes an array and makes it into a string then using that string i want to create a local text file the user downloads. i have tried using this method

   function createFile(){ //creates a file using the fileLIST list 
    var output= 'Name \t Status\n'+ fileLIST[0][0].name+'\t'+fileLIST[0][1]+'\n';
    var Previous = fileLIST[0];
    for (var i=1; i<fileLIST.length; i++)
        if (fileLIST[i][1] =='none' || fileLIST[i][1] == Previous[1])
            continue
        else {
            Previous = fileLIST[i]
            output = output + fileLIST[i][0].name +'\t'+fileLIST[i][1] + '\n';}

    window.open("data:text/json;charset=utf-8," + escape(output));//should create file
    display();  }

我正在使用chrome作为浏览器。还有我喜欢JS或HTML5的答案。

i am using chrome as my browser. also i would prefer JS or HTML5 answer.

提前谢谢你

推荐答案

我最终使用这个代码。它创建一个链接来下载文件的URL。

i ended up using this code instead. it creates a link to download the url of the file.

     window.URL = window.webkitURL || window.URL;
    window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||       window.MozBlobBuilder;
    file = new WebKitBlobBuilder();
    file.append(output); 
    var a = document.getElementById("downloadFile");
    a.hidden = '';
    a.href = window.URL.createObjectURL(file.getBlob('text/plain'));
    a.download = 'filename.txt';
    a.textContent = 'Download file!';
}

这种方式增加了更少的网站,使其成为一个更轻的网站慢连接。
我的html有一个空的div,这附加了。

also this way adds less to the website making it a lighter website for slow connections. my html has a empty div in which this appends to.

   <div class ='paginationLIST' id='pagination'></div>

这篇关于使用JS和html5从String创建文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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